我能获得一个"组分QUOT;按类型? [英] Can I gain access to a "component" by type?
问题描述
我有这样一个类:
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;}
};
基本上是实体的所有可能的类型的组件的容器(与其他的东西,太)。我的问题是,我有超过15个不同的组件和我不喜欢复制和放大器;这样贴线。
我在寻找类似:
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>();
要获得我所需要的组件。我接过一看的boost ::元组是很酷,但它允许访问使用整数的关键。我可以在每个组件*类使用公共静态常量整数,并获得这样的访问:
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>();
但我必须确保使用不同的ID为每个组件,这就是坏mantainance。
but then I have to make sure to use different ids for each component and that's bad for mantainance.
有没有办法使用魔法(即模板),让图型该类型的值 myEntity.get&LT;&的Component1 GT;?()
按预期工作
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?
我也想有,因为O(1)访问组件 myEntity所:: GET&LT; T&GT;
与15经常使用(而不是20个组件是有道理反正谈论的复杂性),但是,这不是强制性的。
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.
推荐答案
我非常接近问同样的问题:我的boost ::融合::地图
或的boost ::融合::设为
是矫枉过正,我真的不喜欢超长的模板参数列表,不必设置一个宏,如果我有10个以上在我的容器。我有这样的事情了:
I very nearly asked the same question: for me boost::fusion::map
or boost::fusion::set
are overkill and I really don't like the extra-long template parameter lists and having to set a macro if I have more than 10 in my container. I went with something like this:
template <class T>
struct Holder
{
T t;
};
struct A {};
struct B {};
struct Aggregate
:
Holder<A>,
Holder<B> // add as many more as you need here
{
template <class T>
T &get()
{
return this->Holder<T>::t;
}
};
Aggregate a;
a.get<A>();
a.get<B>();
这篇关于我能获得一个&QUOT;组分QUOT;按类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!