Assigning a unique integral identifier for types, compilation time

I wonder if some means of template metaprogramming allows you to assign unique integral identifiers for different types, that is, something like this:

class Type; enum { id = identifier<Type>() /* or identifier<Type>::id, ... */ }; static_assert(id == identifier<Type>(), "..."); 

The tough part, I think, is that the identifier must remain unchanged in one compilation (which does not necessarily match the compilation unit). But of course, since I don’t know the technique or, if at all possible, I really don’t know which is the hardest part.

Edit: How in one compilation unit?

+1
source share
2 answers

Take a look at Modern C ++ Design by Andrei Alescandrescu. He pretty deeply analyzes this problem, actively participating in the template metaprogram, in one of the chapters on abstract factories. The conclusion is that there is no absolutely portable way to map a C ++ type to an integral type.

0
source

You can use typeid at run time for classes with virtual functions.

Other types do not have the necessary representation and global order, the compiler does not have the ability to know all compilation units, and the linker does not have a concept of type. The most common solution is to use Boost.MPL to create a vector of all interesting types and use the index in this vector as an identifier.

+1
source

Source: https://habr.com/ru/post/1400759/


All Articles