UTCNWannabe
UTCNWannabe

Reputation: 13

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!

Upvotes: 1

Views: 192

Answers (2)

asmmo
asmmo

Reputation: 7100

You may learn and use variadic templates, as follows

#include <iostream>

template <typename ... Types>
size_t func(Types ... args){

    return sizeof...(args);
}

int main()
{
    std::cout << func(1, 2, 3, 4);
}

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 141940

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);
}

Upvotes: 4

Related Questions