Reputation: 234
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 {};
Upvotes: 0
Views: 139
Reputation: 56863
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 :)
Acknowledgment: Some code "stolen" from here.
Upvotes: 3