Can we specify default parameter values for macro parameters?
I know there isn't any type-checking, so I expect the default value to be nothing more than just some text used by the preprocessor for macro expansion in instances where the parameter value is not specified.
You are looking for a macro overload mechanism which is provided in e.g. Boost.PP's facilities.
#define MACRO_2(a, b) std::cout << a << ' ' << b;
#define MACRO_1(a) MACRO_2(a, "test") // Supply default argument
// Magic happens here:
#define MACRO(...) BOOST_PP_OVERLOAD(MACRO_, __VA_ARGS__)(__VA_ARGS__)
Demo. The number of arguments is concatenated with the macro name, which can easily be implemented without Boost as follows:
#define VARGS_(_10, _9, _8, _7, _6, _5, _4, _3, _2, _1, N, ...) N
#define VARGS(...) VARGS_(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define CONCAT_(a, b) a##b
#define CONCAT(a, b) CONCAT_(a, b)
And
#define MACRO_2(a, b) std::cout << a << ' ' << b;
#define MACRO_1(a) MACRO_2(a, "test") // Supply default argument
#define MACRO(...) CONCAT(MACRO_, VARGS(__VA_ARGS__))(__VA_ARGS__)
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With