没有RTTI的类标识

ppr*_*ger 13 c++ identity rtti

我在互联网上的某个地方找到了一个简单的解决方案,没有内置的C++ RTTI.

template <typename T>
class Identity {
public:
    static int64_t id()
    {
        static int64_t dummy;
        return reinterpret_cast<int64_t>(&dummy);
    }
};
Run Code Online (Sandbox Code Playgroud)

当我们需要一些类ID时,我们只需使用:

Identity<OurClass>::id();
Run Code Online (Sandbox Code Playgroud)

我想知道,有没有碰撞?它可以为不同的类返回相同的ID,还是为相同的类返回不同的ID?我用g ++尝试了这个带有不同优化值的代码,一切似乎都没问题.

Mat*_* M. 12

首先:有一个专门用于包含指针的整数类型:

  • intptr_t
  • 在C++ 11中 uintptr_t

其次,即使在gcc实践中它们是相同的,指向对象的指针的大小和函数指针(或指向成员的指针)的大小也可能不同.因此,使用特定对象而不是方法本身(对于标准一致性)会更好.

第三,它只给你身份,而RTTI更丰富,因为它知道给定对象可以被强制转换的所有子类,甚至允许跨虚拟继承的交叉转换或强制转换.

不过,我认为修正后的版本很有用:

struct Foo {
    static intptr_t Id() {
        static boost::none_t const Dummy = {};
        return reinterpret_cast<intptr_t>(&Dummy);
    }
};
Run Code Online (Sandbox Code Playgroud)

在层次结构中,有一个virtual返回该ID 的函数.

为了完整起见,我会提到Clang和LLVM有自己的方法来处理没有RTTI的对象识别.你可能想了解他们实施的方式isa,castdyn_cast 在这里.