I have a class like this:
class Component1 {...};
class Component2 {...};
class Component3 {...};
class Entity
{
Component1 c1;
Component2 c2;
Component3 c3;
public:
Component1& get_c1() { return c1;}
Component2& get_c2() { return c2;}
Component3& get_c3() { return c3;}
};
Basically the Entity is a container of all possible types of components (with other stuff, too). My problem is that I have more than 15 different components and I don't like to copy&paste lines this way. I'm looking for something like:
myEntity.get<Component1>();
to obtain the component I need. I took a look at boost::tuple which is cool but it allows access using an integer as key. I could use a public static const integer in each Component* class and gain access like this:
myEntity.get<Component1::id>();
but then I have to make sure to use different ids for each component and that's bad for mantainance.
Is there a way to "map" a type to a value of that type using magic (i.e. templates), so that
myEntity.get<Component1>()
works as expected?
I'd also like to have O(1) access to a component since the myEntity::get<T>
is used very often (not that with 15-20 components makes sense talking about complexity anyway) but that's not mandatory.
Consider using a boost::fusion::map, this allows you to map types to values, for example:
I think the above is correct, sorry about brevity, not easy on iPhone!
EDIT: Actually, as pointed out by @Eugine below,
boost::fusion::set
is a better match, similar thing to above:I might be wrong, but it seems to me what you're looking for is Boost.Variant
But, if you want ALL the components to be available and have one instance of each component, then variants are not for you.