buttonsrtoys
buttonsrtoys

Reputation: 2771

Possible to pass comma and args into C++ macro?

Wondering if it's possible to assign a C++ macro two values separated by a comma and use this macro to later define two parameters passed to a macro?

E.g., for the macro

#define ADD_TWO(first, second) first + second

This works:

    int foo = ADD_TWO(0, 42);

But this doesn't

#define ZERO_COMMA_FORTY_TWO 0,42
int bar = ADD_TWO(ZERO_COMMA_FORTY_TWO);

Is there a way to define a macro as two or more parameters to another macro?

EDIT: Environment is VS2017

Upvotes: 3

Views: 508

Answers (1)

hlt
hlt

Reputation: 6317

You cannot do this directly. A macro with two arguments expects two arguments to be passed, and ZERO_COMMA_FORTY_TWO is seen as one argument. However, you can add an additional layer of indirection to expand the macros that are passed in via variadic macros:

#define ADD_TWO_IMPL(first, second) first + second
#define ADD_TWO(...) ADD_TWO_IMPL(__VA_ARGS__)
#define ZERO_COMMA_FORTY_TWO 0, 42

Then, both of these work

int foo = ADD_TWO(0, 42);
int bar = ADD_TWO(ZERO_COMMA_FORTY_TWO);

Apparently, MSVC has a bug that causes it to reject this code, but we can work around that (with more indirection):

#define ADD_TWO_IMPL(first, second) first + second
#define UNPACK(macro, args) macro args
#define ADD_TWO(...) UNPACK(ADD_TWO_IMPL, (__VA_ARGS__))

This version compiles on MSVC, GCC, and Clang

Upvotes: 4

Related Questions