简体   繁体   中英

Compile time generated constant type ID

I'm writing an event system as a part of a hobby project, a 2D game engine. As part of the event system design, I need to map objects in base of what templated derived class they represent. To better illustrate the problem, consider the following simplified code:

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*/

There is no actual problem with this code, but the requirement of manually passing a number identifying the type of each derived class instance is very cumbersome and quite error prone. What I want is to automatically generate the typeId from the type of T at compile time:

Derived<int> obj1;
Derived<float> obj2;
Derived<float> obj3;

if(Base::compareIfSameType(&obj1, &obj2))
    //do something...

Putting aside the question of the wisdom of a design that requires comparing type for equality, you can do that with typeid . No need to write your own. Base* a and Base* b point to objects that have the same derived type if typeid(*a) == typeid(*b) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM