C / C ++ preprocessor宏可以有默认参数值?

问题描述:

我们能为宏观参数指定默认的参数值?

Can we specify default parameter values for macro parameters?

我知道没有任何类型检查,所以我期望的默认值是没什么不仅仅是由preprocessor用于在未指定参数值情况下,宏扩展使用了一些文字了。

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.

您正在寻找这是在例如提供宏超载机制Boost.PP's设施

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)

#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__)

演示