I've got a little test put together that has a couple simple Components that are supposed to be added to an Entity, but the addComponent function isn't working; I think it's got something to do with typeid/component class inheritance, but I'm not sure. It seems to add a single entry to the map of type Component, but nothing else. Any help is much appreciated, thanks!
#include <iostream>
#include <unordered_map>
#include <typeinfo>
using namespace std;
//----------------------------------------------------------------------
//the base component
class Component {
public:
Component() {cout<<"new Component created\n";}
};
//----------------------------------------------------------------------
//a "thing" component
class Thing : public Component {
public:
Thing() {cout<<"new Thing created\n";}
};
//----------------------------------------------------------------------
//a "what" component
class What : public Component {
public:
What() {cout<<"new What created\n";}
};
//----------------------------------------------------------------------
class Entity {
public:
void addComponent(Component* c);
template <typename T> T* getComponent();
int componentCount();
private:
unordered_map<const type_info *, Component *> components;
};
//----------------------------------------------------------------------
void Entity::addComponent(Component* c) {
components[&typeid(*c)] = c;
}
//----------------------------------------------------------------------
template <typename T>
T* Entity::getComponent() {
if(components.count(&typeid(T)) != 0) {
return static_cast<T*>(components[&typeid(T)]);
} else {
return nullptr;
}
}
//----------------------------------------------------------------------
int Entity::componentCount() {
return components.size();
}
//----------------------------------------------------------------------
int main(int argc, char* argv[]) {
Entity e;
e.addComponent(new What());
e.addComponent(new Thing());
cout<<e.componentCount()<<endl;
return 0;
}