我正在编写一个事件系统作为一个业余项目的一部分,一个 2D 游戏引擎。作为事件系统设计的一部分,我需要根据它们所代表的模板化派生类来映射对象。为了更好地说明问题,请考虑以下简化代码:
class Base
{
public:
virtual ~Base(){};
int getTypeId() {return typeId_;}
static bool compareIfSameType(Base *a, Base *b)
{return a->getTypeId() == b->getTypeId();}
protected:
int typeId_;
};
template<typename T>
class Derived : public Base
{
public:
Derived(int typeId) {typeId_ = typeId;}
};
int main()
{
Derived<int> obj1(1);
Derived<float> obj2(2);
Derived<float> obj3(2);
if(Base::compareIfSameType(&obj1, &obj2))
cout << "obj1 and obj2 are of equal type\n";
else cout << "obj1 and obj2 are not of equal type\n";
if(Base::compareIfSameType(&obj2, &obj3))
cout << "obj2 and obj3 are of equal type\n";
else cout << "obj2 and obj3 are not of equal type\n";
}
/*output:
obj1 and obj2 are not of equal type
obj2 and obj3 are of equal type*/
这段代码没有实际问题,但是需要手动传递一个数字来标识每个派生类实例的类型,这非常麻烦并且很容易出错。 我想要的是在编译时自动从 T 的类型生成 typeId:
Derived<int> obj1;
Derived<float> obj2;
Derived<float> obj3;
if(Base::compareIfSameType(&obj1, &obj2))
//do something...
最佳答案
抛开需要比较类型以获得相等性的设计是否明智的问题,您可以使用 typeid
来做到这一点。无需自己编写。 Base* a
和 Base* b
指向具有相同派生类型的对象,如果 typeid(*a) == typeid(*b)
.
关于c++ - 编译时生成常量类型 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19199617/