StackUser
StackUser

Reputation: 319

Can I know how many arguments my function gets?

Given a function in c++, is there any way to get the number of arguments that my function requires? (like argc in main in c language).

For example:

double MyFunction(int x , int y) {   
    int NumOfParam= //.... =2;  
}    

Why would this be useful to me?
For example, I want to write a function that inserts all the parameters of the function into a vector, and I thought doing it with a for loop that iterates through the arguments.

For example:

void MyFunction(int x,int y , int z){  
    std::vector<int> params;  
    for(int i=0; i< ?? ; i++) {  
        params.push_back("ArrayOfMyArguments[i]");
    }
}

Upvotes: 0

Views: 250

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

It seems to me that you come from a JavaScript background, where all functions have an arguments array. C++ is not JavaScript, and it's not possible.

If you want to have a dynamic number of arguments then the solutions are either:

  • parameter packs
  • std::initializer_list
  • Using iterator pairs if you have a sequence from another container
  • C-style variadic functions (where you need a special argument to tell you the number of variadic arguments, or an "end of argument" marker)
  • Or an argc and argv like solution

If all you want to do is to populate a vector, then I rather recommend that you simply populate it directly, either through a loop when and where needed, or through the constructor taking an std::initializer_list (as explained in one of my comments).

If you really need to pass a variable number of arguments to a function, then I recommend parameter packs.

Upvotes: 7

YSC
YSC

Reputation: 40080

What you're looking for is a function-template in conjunction with variadic templates (a/k/a parameter packs):

template<class ... Args>
void f(Args ... args)
{
    std::cout << sizeof...(args) << "\n";
}

int main()
{
    f(0, 1, 2); // prints 3
    f(0, 1, 2, 3, 4); // prints 5
}

This is generally not what you would use by default. Consider using ranges:

template<class Iterator>
void f(Iterator begin, Iterator end)
{
    std::cout << std::distance(begin, end) << "\n";
}

which is more idiomatic.

Upvotes: 9

Related Questions