我有一个实体类、一个基础组件类和一些基础组件派生类。实体类包含一组基本组件指针:
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!
};
我想知道如何映射特定组件 type 及其整数标识符(对于 CPoint 组件类,它将是 0)以便我可以在我的实体类中轻松地将其转换为正确的类型。
示例:假设我已经将一个 CPoint 组件添加到实体组件数组(当然是位置 0),并且我想通过输入组件整数标识符(在本例中为 0)。我想尽可能避免巨大的“转换”案例!
PS:我不想在我的基组件类中使用大量与派生类中的属性相匹配的虚函数。 (我不想在我的基组件类中有一个虚拟 SetPos 函数,而它的位置在 CPoint 类中);
PS#2:正如“etarion”所说,我想要这样的东西:
dynamic_cast<get_type_for(0)*>(obj)
当然,这是我想实现的机制,不知道可不可以。
最佳答案
好吧,我知道一些方法可以实现你想要的那种东西:
- 对于 gcc,您可以使用非标准
typeof(some_type)
函数,它为您提供动态转换类型的类型。参见 here . - 与C++0x有一种模仿 typeof 的标准方法:
decltype(some_type)
- 您可以使用标准的
typeid
为您提供 type_info实现operator==
的类
- boost::variant是其中一条评论中提到的另一种方式(我确实很了解......)
我的2c
关于c++ - 使用数字标识符注册类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934246/