Reputation: 1328
I'd like to do something like this:
#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO(num,...) MYMACRO##num(__VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)
And I expected it to evaluate to "two args". But instead I have
MYMACRONUM_ARGS()(1,1)
Is there a way to do what I want (using visual c++) ?
P.S. Eventually I want to implement logger that dumps all of variables. The next code
int myInt = 7;
string myStr("Hello Galaxy!");
DUMP_VARS(myInt, myStr);
will produce log record "myInt = 7; myStr = Hello Galaxy!"
Upvotes: 4
Views: 3127
Reputation: 2891
You need another macro because macro expansion does not take place near #
or ##
:
#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO_AUX(num,...) MYMACRO##num(__VA_ARGS__)
#define MYMACRO(num,...) MYMACRO_AUX(num, __VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)
#include <stdio.h>
int main(void)
{
puts(GENERATE(0, 1));
return 0;
}
If this is what you're trying to do, but complicated preprocessor tricks are not really safe, as others already said, don't do it unless you really have to.
Upvotes: 7