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
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.
#include
constexpr int CountOccurances(const char* str, char c) {
return str[0] == char(0) ? 0 : (str[0] == c) + CountOccurances(str+1, c);
}
#define NUMARGS(...) (CountOccurances(#__VA_ARGS__, ',') + 1)
int main(){
static_assert(NUMARGS(hello, world) == 2, ":(") ;
return 0;
}
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.