Creating a function that returns a list of objects of a specified type from another list of objects

Hey all. As mentioned in the title, I'm trying to create a function that returns a list of all the objects of the specified type from another list(list as in vector). However, the way in which I have implemented it currently doesn't seem to be working.

The current implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    template<typename T>
    inline std::vector<T*> GameObject::GetGameObjectOfType()
    {
    	std::vector<T*> temp;
    	for (GameObject* g : ObjectList)
    	{
    		if (typeid(g) == typeid(T))
    		{
    			T* t = dynamic_cast<T*>(g);
    			temp.push_back(t);
    		}
    	}
    	return temp;
    }


Edit: T will always be a derived type of GameObject.

Where it is being used:
 
		GameObject::GetGameObjectOfType<Player>()[0]->SetPosition(sf::Vector2f(0, 0));


At the moment, the above line creates a runtime error because the returned vector doesn't have any elements added to it. The error I get is vector subscript out of range.

How should I go about implementing this function so that it doesn't create any errors?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename T>
inline std::vector<T*> GameObject::GetGameObjectOfType()
{
    std::vector<T*> temp;
    
    for( GameObject* g : ObjectList )
    {
        T* t = dynamic_cast<T*>(g); 
        if( t != nullptr ) temp.push_back(t);
    }
    
    return temp;
}
Thanks that's perfect. So if a dynamic cast fails, it returns a nullptr?
Yes; a failed dynamic cast on a pointer yields a nullptr.
Topic archived. No new replies allowed.