Question

I would like to write a macro which have one parameter and add this parameter to an enum and create a class with the same name. Is it possible in C++? If yes, than how?

To make it clearer here is an example what I want to do:

I call the macros like this:

REGISTER(A);
REGISTER(B);
REGISTER(C);

Or call the macros like this:

REGISTER(A, B, C);

And I want to get the preprocessor to generate code like this:

enum X { E_A, E_B, E_C };
class A {};
class B {};
class C {};
Was it helpful?

Solution

Something like this may help:

#define FE_1(WHAT, X) WHAT(X) 
#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)
#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)
#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)
#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)
//... repeat as needed

#define GET_MACRO(_1,_2,_3,_4,_5,NAME,...) NAME 
#define FOR_EACH(action,...) \
  GET_MACRO(__VA_ARGS__,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)

#define REGISTER_ENUM_VALUE(X) E_##X,
#define REGISTER_ENUM(...) enum X { FOR_EACH(REGISTER_ENUM_VALUE, __VA_ARGS__) }
#define REGISTER_CLASS(X) ; class X {}
#define REGISTER(...) REGISTER_ENUM(__VA_ARGS__) FOR_EACH(REGISTER_CLASS, __VA_ARGS__)

REGISTER(A, B, C);

Note that you can not get true variadic FOR_EACH, it will always be limited to a certain maximum amount of parameters for which you are planning and that you implemented manually. At least no-one found a way around it yet :)

Live example

Acknowledgment: Some code "stolen" from here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top