c++ - 动态检查使用可变参数继承的类的类型的最佳方法是什么?

标签 c++ templates variadic-templates

我正在为使用可变参数模板构建游戏对象的 2D 游戏引擎编写实体组件系统。这是对象类,它只是所有组件的容器。我删除了不相关的东西。

template<class ... Components>
class Object : public Components...{
public:
    Object(Game* game) : Components(game)...{

    }
};

组件由对象继承,但我试图找到检查这些组件类型的最佳方法,以便它们可以正确地相互通信。例如,物理组件将包含对象的更新位置。 Drawable 组件需要获得该位置,以便它可以绘制在世界上的正确位置。我想向 Object 添加一个更新功能,以更新每个组件并传输任何可以/需要在当前组件之间传输的信息。

最佳答案

多态性就是你想要的。 只需像这样制作所有组件:

public Object
{
 enum TYPE{
 COMPONENT,,
 GAMEOBJECT,
 ETC,,,
};
Object(TYPE id){m_id = id;}
protected:
  TYPE m_id;
  virtual void Update(void) = 0;

  virtual void Render(void) = 0;

 public:
  void GetTypeOf(void)const{return m_id;}
};

 class Component : Object
 {
  enum COMPONENT_TYPE
 {
  COLLIDER,
  RENDERER,
  ETC,,,,
 };
   Component() : Object (COMPONENT){/**/}
   virtual void Update(void){return;}
   virtual void Render(void){return;}
   };

     class BoxCollider : Component
     {
      BoxCollider(void) : Component(BOXCOLLIDER){/**/}
      void Update(void)
      {
        //to do
         }
       void Render(void)
      {
          //to do
         }
     };

那么你可以简单地拥有一个 Object* 或 Component* 的数据结构 你可以通过这种方式迭代:

   std::vector<Component*>::iterator components = ComponentVector.begin();
   for(;components != ComponentVector.end() ; ++components)
   {
      *(component)->Update();
       *(component)->Render();
        std::cout << "id" << *component->getTypeOf() << std::endl; 
   }

关于c++ - 动态检查使用可变参数继承的类的类型的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415725/

相关文章:

c++ - 可能存在内存泄漏 : new char[strlen()]

c++ - 宏是否分配内存?

c++ - 释放一对 vector 中对象的内存

c++ - 将每种类型包装在模板类中的可变参数模板中

c++ - 匹配可变参数非类型模板

c++ - 在不带参数的可变参数模板中迭代

c++ - 为什么在使用 eigen3 求逆矩阵时得到错误答案

C++ 继承、模板和覆盖

C++ enable_if_t SFINAE

c++ - 如何实现递归 "using"/提取模板参数