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?
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