用于Visual Studio的具有零参数的参数计数宏 [英] Argument counting macro with zero arguments for VisualStudio

查看:129
本文介绍了用于Visual Studio的具有零参数的参数计数宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcc确实支持使用## __VA_ARGS__约定具有零参数的参数计数宏.用gcc编译的以下作品:

gcc does support argument counting macros with zero arguments with the ## __VA_ARGS__ convention. The following works compiled with 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;
}

是否存在与VisualC ++等效的功能,可以与零参数宏一起使用?接受非标准的扩展名或技巧.

Is there an equivalent for VisualC++ that will work with zero arguments macros? Non standard extensions or tricks accepted.

编辑:修复了该示例可与GCC扩展程序和C ++编译器一起使用.

EDIT: Fixed the example to work with GCC extensions and C++ compiler.

推荐答案

下面的示例在VisualStudio 2010和更新的gcc和clang中启用了非标准扩展名,可以很好地工作.在Microsoft编译器中,它假定当参数计数为零时,预处理器将删除AUGMENTER宏中的结尾逗号.这是非标准的,也有报道.在gcc和clang中,它使用了广为人知的## __VA_ARGS__非标准扩展名.

The following example works fine in VisualStudio 2010 and newer, gcc and clang with non standard extensions enabled. In Microsoft compilers it assumes the trailing comma in the AUGMENTER macro will be removed by the preprocessor when arguments count is zero. This is non standard and it has been also reported elsewere. In gcc and clang it uses the widely known ## __VA_ARGS__ non standard extension.

#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;
}

使用实际的编译器, Wandbox

Macros were tested with real compilers, Wandbox and Webcompiler

这篇关于用于Visual Studio的具有零参数的参数计数宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆