Generate unique numbers at compile time

点点圈 提交于 2020-01-02 02:20:29

问题


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?


回答1:


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.




回答2:


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




回答3:


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




回答4:


One way might be to hard-code a placeholder wherever you want a unique number, and then write a small utility to pre-process the files, perhaps keeping the last-used number in a file so it will persist across invocations.



来源:https://stackoverflow.com/questions/9949532/generate-unique-numbers-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!