I’ve found a simple solution somewhere on the internet to an identity class without built-in C++ RTTI.
template <typename T>
class Identity {
public:
static int64_t id()
{
static int64_t dummy;
return reinterpret_cast<int64_t>(&dummy);
}
};
When we need some class ID, we just use:
Identity<OurClass>::id();
I’m wondering, are there any collisions? Can it return the same ID for the different classes, or the different ID for the same classes? I have tried this code with g++ with different optimization values, everything seems ok.
First off: there is such an integral type that is made specifically to contain pointers:
intptr_tuintptr_tSecond, even though in practice on gcc they are equal, the size of a pointer to an object and the size of a function pointer (or pointer to member) might well be different. Therefore it would be better using a specific object rather than the method itself (for Standard conformance).
Third, it only gives you identity, while RTTI is much richer, as it knows about all the subclasses a given object can be cast to, and even allows cross-casts or casts across virtual inheritance.
Still, the corrected version can be useful I guess:
And in hierarchies, having a
virtualfunction returning that ID.For completeness, I’ll mention that Clang and LLVM have their own way of dealing with object identification without RTTI. You may want to read about their way of implementing
isa,castanddyn_casthere.