Variadic macros with zero arguments and commas

Consider this macro:

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

When used with null arguments, it creates bad code because the compiler expects an identifier after the decimal point. Actually, the VC preprocessor is smart enough to remove a comma, but GCC is not. Since macros cannot be overloaded, it seems that this particular case requires a separate macro to get it right, as in:

 #define MAKE_TEMPLATE_Z() template <typename T> 

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

+7
c ++ c c-preprocessor variadic-macros
source share
3 answers

No, because the MAKE_TEMPLATE() macro has no null arguments at all; it has one argument containing zero tokens.

Older preprocessors, apparently including GCC at the time of writing this answer, sometimes interpret the empty argument list, as you might expect, but consensus has moved toward a narrower, narrower extension that more closely matches the standard.

To get the answer below, 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 really supports this, just not transparently.

Syntax:

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

In any case, both options support variation patterns in C ++ 0x mode, which is much preferable.

+9
source share

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

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

If __VA_ARGS__ empty, the GCC preprocessor deletes the previous comma.

+1
source share

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

As with variable macros with zero arguments, there are tricks to detect this and the macro program around it. Googel for empty arguments .

0
source share

All Articles