cez*_*tko 3 c++ macros visual-c++
gcc支持使用## __VA_ARGS__约定对零参数计数宏.以下使用gcc编译的工作:
#include <stdio.h>
#define NARGS(...) __NARGS(0, ## __VA_ARGS__, 5,4,3,2,1,0)
#define __NARGS(_0,_1,_2,_3,_4,_5,N,...) N
int main()
{
printf("%d\n", NARGS()); // prints 0
printf("%d\n", NARGS(1)); // prints 1
printf("%d\n", NARGS(1, 2)); // prints 2
return 0;
}
Run Code Online (Sandbox Code Playgroud)
VisualC++ 2010是否有与零参数宏一起使用的等价物?接受非标准扩展或技巧.
编辑:修复了使用GCC扩展和C++编译器的示例.
cez*_*tko 10
以下示例在VisualStudio 2010和更新,gcc和clang中启用非标准扩展时工作正常.在Microsoft编译器中,它假定当参数count为零时,预处理器将删除AUGMENTER宏中的尾随逗号.这是非标准的,并且还有其他报道.在gcc和clang中,它使用广为人知的## __VA_ARGS__非标准扩展.
#include <stdio.h>
#ifdef _MSC_VER // Microsoft compilers
#define EXPAND(x) x
#define __NARGS(_1, _2, _3, _4, _5, VAL, ...) VAL
#define NARGS_1(...) EXPAND(__NARGS(__VA_ARGS__, 4, 3, 2, 1, 0))
#define AUGMENTER(...) unused, __VA_ARGS__
#define NARGS(...) NARGS_1(AUGMENTER(__VA_ARGS__))
#else // Others
#define NARGS(...) __NARGS(0, ## __VA_ARGS__, 5,4,3,2,1,0)
#define __NARGS(_0,_1,_2,_3,_4,_5,N,...) N
#endif
int main()
{
// NARGS
printf("%d\n", NARGS()); // Prints 0
printf("%d\n", NARGS(1)); // Prints 1
printf("%d\n", NARGS(1, 2)); // Prints 2
fflush(stdout);
#ifdef _MSC_VER
// NARGS minus 1
printf("\n");
printf("%d\n", NARGS_1(1)); // Prints 0
printf("%d\n", NARGS_1(1, 2)); // Prints 1
printf("%d\n", NARGS_1(1, 2, 3)); // Prints 2
#endif
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用真正的编译器Wandbox和Webcompiler测试了宏
| 归档时间: |
|
| 查看次数: |
1985 次 |
| 最近记录: |