Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time constant id

Given the following:

template<typename T> class A { public:     static const unsigned int ID = ?; }; 

I want ID to generate a unique compile time ID for every T. I've considered __COUNTER__ and the boost PP library but have been unsuccessful so far. How can I achieve this?

Edit: ID has to be usable as the case in a switch statement

Edit2: All the answers based on the address of a static method or member are incorrect. Although they do create a unique ID they are not resolved in compile time and therefore can not be used as the cases of a switch statement.

like image 618
David Avatar asked Sep 26 '11 22:09

David


People also ask

What is a compile-time constant?

A compile-time constant is a value that can be (and is) computed at compile-time. A runtime constant is a value that is computed only while the program is running. If you run the same program more than once: A compile-time constant will have the same value each time the application is run.

What are compile-time constants in Java?

4.1. Compile-Time Constants. A Java variable is a compile-time constant if it's of a primitive type or String, declared final, initialized within its declaration, and with a constant expression. Strings are a special case on top of the primitive types because they are immutable and live in a String pool.

How do you calculate compile-time?

Compile time calculation can be done using template metaprogramming. This will output the time required by g++ file_name. cpp to compile.

What is compile-time and runtime C#?

Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.


1 Answers

This is sufficient assuming a standards conforming compiler (with respect to the one definition rule):

template<typename T> class A { public:     static char ID_storage;     static const void * const ID; };  template<typename T> char A<T>::ID_storage; template<typename T> const void * const A<T>::ID= &A<T>::ID_storage; 

From the C++ standard 3.2.5 One definition rule [basic.def.odr] (bold emphasis mine):

... If D is a template and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

like image 118
MSN Avatar answered Sep 20 '22 06:09

MSN