Type check for a varable

I wanna to make a GetComponent function for my gameObject class.

I have a vector contains all Components:
std::vector<Component*> m_components;

So if I wanna to get a Collider component which is a child class of Component class in the vector.
like:

auto c = gameObject.GetComponent<Collider>();

For right now, I just don't know hot to check the the type below

template<typename T,typename Requires = std::enable_if_t<std::is_base_of<Component,T>::value>>
T* GameObject::GetComponent() {
T* newT = nullptr;
for each (T* var in m_components)
{
if (T == (var....?????)) { //how could I check the Type of var
newT = var;
}
}
return newT;
}
Last edited on
Assuming that std::is_polymorphic<Component>::value == true,

1
2
3
4
5
6
for( Component* ptr_component : m_components )
{
    // http://en.cppreference.com/w/cpp/language/dynamic_cast
    T* ptr_t = dynamic_cast<T*>( ptr_component ) ;
    if( ptr_t != nullptr ) { / * ... */ }
}
@JLBorges

this is kind of not work. Because the dynamic_cast can cast all of the member from the m_components. For example. I also have a animation component inside of the m_components. So it is possible to cast the Animation component to a collider component
1
2
3
4
5
// the dynamic type of the object is either collider or a derived class of collider
bool is_collider( component* p ) { return dynamic_cast<collider*>(p) != nullptr ; }

// the dynamic type of the object is collider
bool dynamic_type_is_collider( component* p ) { return p && typeid(*p) == typeid(collider) ; }
Topic archived. No new replies allowed.