C++ – Variadic macros with zero arguments, and commas

cc-preprocessorvariadic-macros

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?

Best Answer

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.

Related Topic