Reputation: 319
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
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:
std::initializer_list
argc
and argv
like solutionIf 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
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