Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unique numbers at compile time

I want to generate unique numbers for each class in my header, primes in my case primes but let's say this should only be consecutive numbers i.e. 1,2,3,4,etc.

Of course I can hardcode these:

struct A { enum { ID = 1; }; };
struct B { enum { ID = 2; }; };
struct C { enum { ID = 3; }; };
struct D { enum { ID = 4; }; };

This is very error-prone since in reality the classes are not that small and if I add a new class in the middle I have to change all the following numbers if I don't want to completely loose the overview of the IDs.

I wish I could do the following:

struct A { enum { ID = get_next_int(); }; };
struct B { enum { ID = get_next_int(); }; };
struct C { enum { ID = get_next_int(); }; };
struct D { enum { ID = get_next_int(); }; };

But since constexpr functions calls can't have side effects afaik, this is impossible. I think using macros such a result is impossible too.

I would also be lucky with something like that:

struct A_id_holder : some_base_counter {};
struct A { enum { ID = A_id_holder::ID; }; };

struct B_id_holder : some_base_counter {};
struct B { enum { ID = B_id_holder::ID; }; };

struct C_id_holder : some_base_counter {};
struct C { enum { ID = C_id_holder::ID; }; };

struct D_id_holder : some_base_counter {};
struct D { enum { ID = D_id_holder::ID; }; };

But honestly, I have no idea how to implement that.

Can I achieve my goal and if yes, how?

like image 846
helami Avatar asked Mar 30 '12 19:03

helami


3 Answers

I think that Boost preprocessor library can do that for you, maybe you should read that: How can I generate unique values in the C preprocessor?

There is an alternative depending on the compiler that you are using, gcc and msvc have a ___COUNTER___ macro that allows sequential number: http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros

like image 86
Mesop Avatar answered Sep 25 '22 04:09

Mesop


Most people do this with the __COUNTER__ macro. But that's nonstandard, and there's only one for the whole program.

Here is a C++ hack I came up with using templates and overloading which is standard-compliant and supports multiple counters.

like image 34
Potatoswatter Avatar answered Sep 28 '22 04:09

Potatoswatter


If you use gcc, you can use the __COUNTER__ macro.

like image 24
Idelic Avatar answered Sep 25 '22 04:09

Idelic