I've seen a few questions asking for a variation on a variadic FOR_EACH
macro. However unfortunately the answers provided are incompatible with VC++10 due to it expanding __VA_ARGS __ as one argument when passed to another macro. Please could someone provide a C++11 compliant (thus forward-compatible) version that still works with VC++10. Perhaps using the "workaround" that is often mentioned, #define EXPAND(x) x
, however I don't know where to put this in order to get, for example, the latter generalised part of this answer to work in VC++10.
To clarify, the intended behaviour is for FOR_EACH(x, a, b, ...)
to produce x(a) x(b), ...
, where x is another macro.
Having now grasped exactly how the VC++10 compiler bug works, I was able to come up with such a macro myself, based on the latter part of this answer.
Example usage:
is the same as
This solution is similar to that in the linked answer, except that the zero length variadic argument list in
FOR_EACH(what, x, ...)
when called with one element caused a spurious comma that makes FOR_EACH_NARG count 2 arguments instead of 1 argument, and theEXPAND
macro workaround is used.The bug in VC++10 is that if
__VA_ARGS__
is passed to a macro within the definition of a variadic macro, it is evaluated after substitution into the macro, causing multiple comma separated arguments to be treated as one. To get around this you must delay argument evaluation until after__VA_ARGS__
is substituted, by wrapping the macro call inEXPAND
, forcing the macro call to be evaluated as a string, substituting__VA_ARGS__
to do so. Only after the substitution intoEXPAND
is the macro called, by which point the variadic arguments are already substituted.P.S. I would be grateful if anyone can suggest a method for compactly producing
FOR_EACH_N
macros for much larger values ofN
.