1

我有一个实体类、一个基础组件类和一些基础组件派生类。实体类包含一个基本组件指针数组:

class CComponent
{
public:
  static unsigned GetType() { return -1; }; //Base identifier 
  //...
};

class CPoint : CComponent
{
  public:
    static unsigned GetType() { return 0; }; //Point identifier 
}

class CEntity
{
private:
  CComponent* aComponents[3];
public:
  // ... 
  //Getter by component ID here!
};

我想知道如何映射特定组件类型及其整数标识符(对于CPoint组件类,它将为 0),以便我可以在我的 Entity 类中轻松地将其转换为正确的类型。

示例:假设我已将 CPoint 组件添加到实体组件数组(当然在位置 0),并且我想通过输入组件整数标识符(在本例中为 0)将其检索为 CPoint(类型转换) . 我想尽可能避免巨大的“开关”案例!

PS:我不想在我的基组件类中使用与派生类中的属性匹配的大量虚拟函数。(我不想在我的基础组件类中有一个虚拟的 SetPos 函数,而它的位置在 CPoint 类中);

PS#2:正如“etarion”所说,我想要这样的东西:

dynamic_cast<get_type_for(0)*>(obj)

当然,这就是我想要实现的机制,不知道能不能实现。

4

1 回答 1

1

好吧,我知道一些方法可以实现您想要的那种东西:

  • 使用 gcc,您可以使用非标准 typeof(some_type)函数,该函数为您提供动态转换类型的类型。见这里
  • 使用C++0x有一种模仿 typeof 的标准方法:decltype(some_type)
  • 您可以使用typeid为您提供type_info类的标准,该类实现operator==
  • boost::variant是其中一条评论中提到的另一种方式(我确实很清楚......)

my2c

于 2011-02-08T16:32:00.487 回答