Search code examples
c++functiontemplatesparametersvariadic-templates

How do I return the number of arguments of a function?


For example if I have

int MyFunction(int,...);//no. of parameters is unknown

And in main()

MyFunction(1,2,3,4);

The returned value should be 4.I've tried stdarg.h but to use that you have to know the number of parameters, so it doesn't hold up for me.Thanks!


Solution

  • Just return the number of arguments in a parameter pack.

    template<typename ...Args>
    unsigned MyFunction(Args... args) {
        return sizeof...(args);
    }
    
    int main() {
        return MyFunction(1,2,3);
    }