While trying to create an Entity-Component-System in C++, I have faced some problems regarding by lack of knowledge on the language.
With a class Entity, that holds the interface IComponent (which acts more like a flag that says "I hold data"), I have a method Add that adds a Component to the Entity if there is not another IComponent of the same class already in it.
Here's an oversimplified sample code:
struct IComponent{};
struct Foo : IComponent{ int x;};
struct Bar : IComponent{ int y; };
class Entity{
vector<IComponent*> entityComponents;
void Add(IComponent* componentToAdd){
if("entityComponents" does not contain the class of "componentToAdd")
entityComponents.add (componentToAdd)
}
}
My expected result would be
Entity e;
Foo f;
Bar b;
Foo anotherF;
e.Add(f); // Works
e.Add(b); // Works
e.Add(anotherF); // Does not work because another
//item in the array already inherits Foo
But I do not know how to get the base class of Foo and Bar from inside the IComponents list and check if they are repeated.
How may I get them? How may I cast an IComponent to a Foo if Foo is in the IComponent list?
Checkout dynamic_cast. You can attempt to cast a pointer to base class to a pointer to a derived class. It fails if the instantiated object is not of type derived and in this case returns null.