c++ - 我可以通过类型访问 "component"吗?

标签 c++ boost types mapping

我有这样一个类:

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 个不同的组件,我不喜欢以这种方式复制和粘贴行。 我正在寻找类似的东西:

myEntity.get<Component1>();

获取我需要的组件。我看了一下 boost::tuple,它很酷,但它允许使用整数作为键进行访问。我可以在每个 Component* 类中使用 public static const integer 并像这样获得访问权限:

myEntity.get<Component1::id>();

但是我必须确保为每个组件使用不同的 ID,这不利于维护。

有没有办法使用魔术(即模板)将类型“映射”到该类型的值,以便 myEntity.get<Component1>()是否按预期工作?

myEntity::get<T> 以来,我还希望能够以 O(1) 的时间访问组件经常使用(并不是说有 15-20 个组件就可以讨论复杂性),但这不是强制性的。

最佳答案

考虑使用 boost::fusion::map,这允许您将类型映射到值,例如:

typedef fusion::map<pair<Component1, Component1>, pair<Component2, Component2> etc.> map_t;
map_t m(make_pair<Component1>(Component()), make_pair<Component2>(Component2()));
// to access
at_key<Component1>(m); // reference to instance of Component1

我认为以上是正确的,抱歉简洁,在 iPhone 上不容易!

编辑:实际上,正如下面@Eugine 所指出的,boost::fusion::set 是一个更好的匹配,与上面类似:

typedef fusion::set<Component1, Component2, etc.> set_t;
set_t s(Component1(), Component2());
// to access
at_key<Component1>(s); // reference to instance of Component1

关于c++ - 我可以通过类型访问 "component"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5904680/

相关文章:

c++ - double 和 NaN 的比较结果是什么?

sql - 转换到自定义域 PostgreSQL

sql-server - 如何解决 Pandas 中的错误“远程过程调用协议(protocol)流中传入的表格数据流不正确”

c++ - 如何在 boost::filesystem 中使用 copy_file?

database - 数字 (12,2) 类型的 Postgresql 字符

c++ - 计算内存中的二维数组

c++ - SFML 碰撞检测只在原点工作?

c++ - 如何使用 QStyle.drawControl() 呈现红色按钮?

c++ - boost asio SSL 服务器错误 : called a function you should not call

c++ - 如何从 Boost Spirit 中的函数中抛出 expectation_failure?