#include "stdio.h"
#define TEST1(str,...) printf(str, ##__VA_ARGS__)
#define TEST2(...) printf("test", ##__VA_ARGS__)
int main()
{
TEST1("test");
TEST2();
return 0;
}
最近遇到个奇怪可变参宏展开的问题,研究了一天,发现g++的可变参宏展开可能有BUG,就是当宏参数只有可变参时,使用##不能正确消除前面的逗号。
比如上述代码,在g++使用C++11编译时,TEST2()这一行编译报错:error: expected primary-expression before ‘)’ token
实际就是##__VA_ARGS__为空时没有正确消除前面的逗号。
但只要不使用C++11编译(14和17我也试了也出错),就是正确的。
并且我在VS 2013下面也试了下,VS也是正常的。
不知道大家有没有遇到过类似的问题,有没有什么解决办法
#################################################################
上个例子有歧义,我把例子稍微改一下,现象和结果都是一样的,也是TEST1正确,TEST2报错
#include "stdio.h"
#define TEST1(str,...) printf(str); printf("test", ##__VA_ARGS__)
#define TEST2(...) printf("test", ##__VA_ARGS__)
int main()
{
TEST1("test");
TEST2();
return 0;
}
##
消除前面的逗号,
只是一些编译器的扩展,不是标准C++的内容。
C++20引入了__VA_OPT__
,可以用来自动添加或消除逗号。
From https://en.cppreference.com/w/cpp/preprocessor/replace
Note: some compilers offer an extension that allows ## to appear after a comma and before VA_ARGS, in which case the ## does nothing when the variable arguments are present, but removes the comma when the variable arguments are not present: this makes it possible to define macros such as fprintf (stderr, format, ##VA_ARGS)
test2里面本来也没有逗号啊
你把##去掉试试