Instead the template trick you talk about (static getID with a counter++ for each class) I use this:
// In Entity class...
std::unordered_map<std::type_index, std::list<std::weak_ptr<Component>>> mComponentArray;
So the type_index can be retrieved doing:
std::typeid(T)
... in the template methods, for example:
template <typename T>
bool Entity::HasComponent() const
{
if(mComponentArray.count(std::typeid(T)))
{
return (! mComponentArray.at(std::typeid(T)).empty());
}
return false;
}
--------------------
I store too a list in the EntityManager to get fast all entities which have a specific component attached:
// In EntityManager class ...
std::unordered_map<std::type_index, std::list<std::weak_ptr<Entity>>> mEntityComponentContainer;
template <typename T>
auto EntityManager::GetEntities() -> std::list<std::weak_ptr<Entity>>&
{
if(EntityManager::HasEntities<T>())
{
return EntityManager::mInstance->mEntityComponentContainer.at(std::typeid(T));
}
return EntityManager::mInstance->mEntityComponentContainer[std::typeid(T)];
}
then it can be used for example with this:
template <typename T>
void EntityManager::ForEach(const function<void(std::weak_ptr<Entity>)> function)
{
for(auto& iEntity : GetEntities<T>())
{
function(iEntity);
}
}