C++ preprocessor __VA_ARGS__ number of arguments

后端 未结 12 2238
一向
一向 2020-11-22 08:03

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

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:36

    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.

提交回复
热议问题