0

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

1 回答 1

1

抛开需要比较类型是否相等的设计是否明智的问题,您可以使用typeid. 无需自己编写。Base* aBase* b指向具有相同派生类型的对象 if typeid(*a) == typeid(*b)

于 2013-10-05T15:56:52.907 回答