具有可变数目的参数的宏-参数列的宏定义方法。

写给日志帮助宏,打日志经常需要格式化字符串,类似:DEBUG_STR(L"value = %d, error = %d.", val, error);

so,定义方法如下:

来自:http://docs.oracle.com/cd/E19205-01/821-0389/bkacd/index.html

C++ 编译器接受以下形式的 #define 预处理程序指令。


#define identifier (...) replacement_list
#define identifier (identifier_list, ...) replacement_list

如果列出的宏参数以省略号结尾,那么该宏的调用允许使用除了宏参数以外的其他更多参数。其他参数(包括逗号)收集到一个字符串中,宏替换列表中的名称 __VA_ARGS__ 可以引用该字符串。以下示例说明了如何使用可变参数列表的宏。


#define debug(...) fprintf(stderr, __VA_ARGS__)
#define showlist(...) puts(#__VA_ARGS__)
#define report(test, ...) ((test)?puts(#test):
                        printf(__VA_ARGS__))
debug(“Flag”);
debug(“X = %d
”,x);
showlist(The first, second, and third items.);
report(x>y, “x is %d but y is %d”, x, y);

其结果如下:


fprintf(stderr, “Flag”);
fprintf(stderr, “X = %d
”, x);
puts(“The first, second, and third items.”);
((x>y)?puts(“x>y”):printf(“x is %d but y is %d”, x, y));
 

总得来讲:

#define DEBUG_STR (...) logfunc(_VA_ARGS_)

... 和 _VA_ARGS_

原文地址:https://www.cnblogs.com/lebronjames/p/3193508.html