-
Notifications
You must be signed in to change notification settings - Fork 239
Macro meta programming
Raymond Chen edited this page May 14, 2019
·
3 revisions
WIL provides some macros to assist with macro meta-programming.
The WI_FLATTEN
macro takes a variable number of arguments and removes the parentheses.
#define WI_FLATTEN(...) __VA_ARGS__
The WI_PASTE
macro takes two arguments. It expands the two arguments, then pastes the results.
Example:
#define apple_pie 3.14
#define flavor apple
double pie = WI_PASTE(flavor, _pie); // expands to 3.14
The WI_ARGS_COUNT
macro takes up to 99 arguments and expands to the number of arguments it was passed.
Example:
int value = WI_ARGS_COUNT(x, y, z); // expands to 3
The WI_FOREACH
macro applies its first parameter to up to 99 remaining parameters.
Example:
#define CHECK(value) CheckValue(value);
#define CHECK_EACH(...) WI_FOREACH(CHECK, __VA_ARGS__)
CHECK_EACH(1, 2, 3)
// expands to
CheckValue(1); CheckValue(2); CheckValue(3);
The WI_MACRO_DISPATCH
expands a macro whose name is computed by suffixing its first parameter with the number of additional parameters (up to 99). The computed macro is then expanded with the additional parameters as its parameters.
Example:
#define CHECK0() Empty()
#define CHECK1(x) Alpha(x)
#define CHECK2(x, y) Beta(x, y)
#define CHECK3(x, y, z) Gamma(x,y,z)
WI_MACRO_DISPATCH(CHECK, 12, 34) // expands to CHECK2(12, 34)
// which expands to Beta(12, 34)