Search code examples
c++c++11c-preprocessorvariadic-macros

variadic macro - optional initializer expression


I want a macro that declares an int with a given name and optional initializer expression.

I tried using this answer on Stack Overflow but with no success.

This is what I tried:

#define macro(...) int FIRST(__VA_ARGS__)(REST(__VA_ARGS__))

when used like this there are no problems:

macro(foo);

but when given an initializer there are errors:

macro(foo, 42);

The alternative - of just using __VA_ARGS__ gives a warning from -pedantic in GCC when there are no arguments.

How can I fix this?

And is it also possible to avoid the () braces when there is no initializer expression - meaning no zero initialization but default?

Note that my real use case is not just for int but for any type and using a third party like boost is not an option.


Solution

  • In the end I ended up with the following: link

    I forward the __VA_ARGS__ to a variadic template because my problem wasn't exactly what I described here (as suggested in the comments) - but the problems when not supplying an initializer persisted - so I silenced the warnings in the header for GCC with #pragma GCC system_header and for Clang I used _Pragma() for -Wgnu-zero-variadic-macro-arguments. MSVC wasn't a problem.

    I also fell victim to the most vexing parse as @MSalters points out in his answer.