I have a generic method in C#:
public T GetComponent<T>() where T : Component {
foreach (Component component in this.components)
if (component is T c)
return c;
return default(T);
}
I want to translate it in C++:
template<typename T>
T* GameObject::getComponent() const {
if (!std::is_base_of<Component, T>::value)
return nullptr;
for (auto i = this->components->begin(); i != this->components->end(); i++)
if (typeid(*i) == typeid(T))
return dynamic_cast<T>(*i);
return nullptr;
}
But it seems like neither typeid
nor dynamic_cast
cannot deal with generic types. How can I achieve it?
EDIT:
Component* GameObject::getComponent(const type_info& type) const {
for (auto i = this->components->begin(); i != this->components->end(); i++)
if (typeid(*i) == type)
return *i;
return nullptr;
}
Possible usage:
cg::SpriteRenderer2D* renderer = (cg::SpriteRenderer2D*)getComponent(typeid(cg::SpriteRenderer2D));
The only problem is that there is no check if the passed type derives Component
. Also I'm not sure if I have to dereference i
two times so typeid(**i)
. The first one from iterator
to Component*
. The second one from Component*
to Component
. Or I store a list of Component&
.