VisualStudio 2010的参数计数宏零参数 [英] Argument counting macro with zero arguments for VisualStudio 2010

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

问题描述

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 ++ 2010是否有等效项,可以使用零参数宏?

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

EDIT :修复了使用GCC扩展和C ++编译器的示例。

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

推荐答案

以下示例在VisualStudio 2010及更高版本,gcc和clang中使用非标准扩展启用。在Microsoft编译器中,假定当参数count为零时,预处理器将删除AUGMENTER宏中的尾随逗号。这是非标准的,也已报告elsewere。在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 Webcompiler

Macros were tested with real compilers, Wandbox and Webcompiler

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

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