Simple question for which I could not find answer on the net. In variadic argument macros, how to find the number of arguments? I am okay with boost preprocessor, if it has the solution.
If it makes a difference, I am trying to convert variable number of macro arguments to boost preprocessor sequence, list, or array for further reprocessing.
I'm assuming that each argument to VA_ARGS will be comma separated. If so I think this should work as a pretty clean way to do this.
Worked for me on godbolt for clang 4 and GCC 5.1. This will compute at compile time, but won't evaluate for the preprocessor. So if you are trying to do something like making a FOR_EACH, then this won't work.
this works with 0 arguments with gcc/llvm. [links are dumb]
Visual Studio seems to be ignoring the ## operator used to consume the empty argument. You can probably get around that with something like
With msvc extension:
Works for 0 - 32 arguments. This limit can be easily extended.
For convenience, here's an implementation that works for 0 to 70 arguments, and works in Visual Studio, GCC, and Clang. I believe it will work in Visual Studio 2010 and later, but have only tested it in VS2013.
This is actually compiler dependent, and not supported by any standard.
Here however you have a macro implementation that does the count:
I usually use this macro to find a number of params:
Full example:
It is completely valid C99 code. It has one drawback, though - you cannot invoke the macro
SUM()
without params, but GCC has a solution to it - see here.So in case of GCC you need to define macros like this:
and it will work even with empty parameter list