我有一个实体类、一个基础组件类和一些基础组件派生类。实体类包含一个基本组件指针数组:
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)
当然,这就是我想要实现的机制,不知道能不能实现。