c++ - 编译时生成常量类型 ID

标签 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...

最佳答案

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

关于c++ - 编译时生成常量类型 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19199617/

相关文章:

c++ - 获取数组中的多个输入

c++ - 如何使用可变参数模板在 C++11 中生成左关联表达式(也称为左折叠)?

c++ - 复杂的运算符重载和模板

c++ - Switch 语句可变模板扩展

c++调用模板类的特定模板构造函数

c++ - SFINAE 的问题

c++ - RAII std::vector 设计难题

c++ - C++ 运行时系统如何知道对象何时超出范围

c++ - 哪些文件属于 CDT 托管构建中的构建目标?

云中的 C++。 Microsoft Azure 上的卡萨布兰卡 REST 服务