Variadic macros with zero arguments, and commas

房东的猫 提交于 2020-01-24 02:21:07

问题


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?


回答1:


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.




回答2:


In case of GCC you need to write it like this:

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

If __VA_ARGS__ is empty, GCC's preprocessor removes preceding comma.




回答3:


First of all beware that variadic macros are not part of the current C++. It seems that they will be in the next version. At the moment they are only conforming if you program in C99.

As of variadic macros with zero arguments, there are tricks à la boost to detect this and to macro-program around it. Googel for empty macro arguments.



来源:https://stackoverflow.com/questions/3563184/variadic-macros-with-zero-arguments-and-commas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!