Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C/C++ preprocessor macros have default parameter values? [duplicate]

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.

like image 724
Giffyguy Avatar asked Nov 20 '14 21:11

Giffyguy


1 Answers

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.

like image 175
Columbo Avatar answered Sep 28 '22 11:09

Columbo