具有零参数和逗号的可变参数宏 [英] Variadic macros with zero arguments, and commas

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

问题描述

考虑此宏:

#define MAKE_TEMPLATE(...) template <typename T, __VA_ARGS__ >

与零参数一起使用时,它会生成错误的代码,因为编译器期望逗号后有一个标识符.实际上,VC的预处理器足够聪明,可以删除逗号,但GCC却不是. 由于宏无法重载,因此在这种特殊情况下,似乎需要一个单独的宏才能正确处理它,如下所示:

#define MAKE_TEMPLATE_Z() template <typename T>

有没有什么方法可以使它在不引入第二个宏的情况下工作?

解决方案

否,因为宏调用MAKE_TEMPLATE()根本没有零自变量;它有一个包含零个令牌的参数.

较早的预处理器,显然是在最初编写此答案时包含GCC的,有时会按您希望的那样解释一个空的参数列表,但共识已朝着更严格,更狭窄的扩展发展,从而更符合标准./p>

要获得以下答案,请在省略号前定义一个附加的宏参数:

   #define MAKE_TEMPLATE(UNUSED, ...) template <typename T, ## __VA_ARGS__ >

,然后在列表不为空时始终在第一个参数前添加逗号:

   MAKE_TEMPLATE(, foo )

旧答案

根据 http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html ,GCC确实支持此功能,只是不透明.

语法是:

   #define MAKE_TEMPLATE(...) template <typename T, ## __VA_ARGS__ >

无论如何,两者都支持C ++ 0x模式下的可变参数模板,这是更可取的.

Consider this macro:

#define MAKE_TEMPLATE(...) template <typename T, __VA_ARGS__ >

When used with zero arguments it produces bad code since the compiler expects an identifier after the comma. Actually, VC's preprocessor is smart enough to remove the comma, but GCC's isn't. Since macros can't be overloaded, it seems like it takes a separate macro for this special case to get it right, as in:

#define MAKE_TEMPLATE_Z() template <typename T>

Is there any way to make it work without introducing the second macro?

解决方案

No, because the macro invocation MAKE_TEMPLATE() does not have zero arguments at all; it has one argument comprising zero tokens.

Older preprocessors, apparently including GCC at the time this answer was originally written, sometimes interpreted an empty argument list as you'd hope, but the consensus has moved toward a stricter, narrower extension which more closely conforms to the standard.

To get the answer below to work, define an additional macro parameter before the ellipsis:

   #define MAKE_TEMPLATE(UNUSED, ...) template <typename T, ## __VA_ARGS__ >

and then always put a comma before the first argument when the list is not empty:

   MAKE_TEMPLATE(, foo )

Old answer

According to http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html, GCC does support this, just not transparently.

Syntax is:

   #define MAKE_TEMPLATE(...) template <typename T, ## __VA_ARGS__ >

Anyway, both also support variadic templates in C++0x mode, which is far preferable.

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

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