I have a abstract component class and an entity class with a vector full of components (the derived possibilities). I want to be able to lookup components. Is it better to look them up by type or by string?
ComponentA* component = entity.getComponent<ComponentA>();
// vs
ComponentA* component = entity.getComponent( "ComponentA" );
In both instances I'll need a vtable, but only in the later will I need to implement some sort of getName
function for every derived class.
Consider this declaration:
template<typename T>
T * getComponent();
Different T
s, different return types and you can assign the returned value directly to a variable of the right type.
It could work. So far so good.
Now consider this declaration:
?? getComponent(std::string);
Or this one if you prefer:
?? getComponent (const char *);
What should be the return type? The best you can do is to use a common base class of your components (if any exists) and cast it within the context of the caller each and every time. I cannot imagine anything more annoying actually.
The other way around you can use it is by returning a void *
but I discourage it.
You can even add a second parameter that is a callable object to which you pass the right type (overload operator()
or make it a template), but it will make everything a bit more confusing at the call point.
Otherwise you can make your function a template one to set at the call point directly the return type but... Wait... Aren't we turning towards the first case? Add the template parameter, remove the function parameter for it's redundant now and what you get is:
template<typename T>
T * getComponent();
I'd say that this is already enough to decide what's the best bet.