How can I write a function that accepts a variable number of arguments? Is this possible, how?
If you know the range of number of arguments that will be provided, you can always use some function overloading, like
f(int a)
{int res=a; return res;}
f(int a, int b)
{int res=a+b; return res;}
and so on...
There is no standard C++ way to do this without resorting to C-style varargs (...
).
There are of course default arguments that sort of "look" like variable number of arguments depending on the context:
void myfunc( int i = 0, int j = 1, int k = 2 );
// other code...
myfunc();
myfunc( 2 );
myfunc( 2, 1 );
myfunc( 2, 1, 0 );
All four function calls call myfunc
with varying number of arguments. If none are given, the default arguments are used. Note however, that you can only omit trailing arguments. There is no way, for example to omit i
and give only j
.
// spawn: allocate and initialize (a simple function)
template<typename T>
T * spawn(size_t n, ...){
T * arr = new T[n];
va_list ap;
va_start(ap, n);
for (size_t i = 0; i < n; i++)
T[i] = va_arg(ap,T);
return arr;
}
User writes:
auto arr = spawn<float> (3, 0.1,0.2,0.3);
Semantically, this looks and feels exactly like an n-argument function. Under the hood, you might unpack it one way or the other.
in c++11 you can do:
void foo(const std::list<std::string> & myArguments) {
//do whatever you want, with all the convenience of lists
}
foo({"arg1","arg2"});
list initializer FTW!
The only way is through the use of C style variable arguments, as described here. Note that this is not a recommended practice, as it's not typesafe and error-prone.
It's possible you want overloading or default parameters - define the same function with defaulted parameters:
void doStuff( int a, double termstator = 1.0, bool useFlag = true )
{
// stuff
}
void doStuff( double std_termstator )
{
// assume the user always wants '1' for the a param
return doStuff( 1, std_termstator );
}
This will allow you to call the method with one of four different calls:
doStuff( 1 );
doStuff( 2, 2.5 );
doStuff( 1, 1.0, false );
doStuff( 6.72 );
... or you could be looking for the v_args calling conventions from C.