编译时生成的常量类型ID

时间:2013-10-05 15:50:48

标签: c++ templates

我正在编写一个事件系统作为业余爱好项目的一部分,一个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...

1 个答案:

答案 0 :(得分:1)

抛开设计智慧的问题,需要比较类型的平等,你可以用typeid做到这一点。无需自己编写。 Base* aBase* b指向typeid(*a) == typeid(*b)具有相同派生类型的对象。