Possible Duplicate:
Variable number of arguments in C++?
May I not set the number of arguments of a function with variable number of arguments? As an example: can the following interface be implemented?
int sum(...) { ... }
sum(1, 2, 3, 4); // return 10
Conventional variadic functions are messy and not type-safe, but in C++11 you can do this cleanly using variadic templates and (compile-time) recursion:
Since it’s a template, this’ll work for any types that have an
operator+defined:However, because the return type of the recursive template function is taken from the first argument only, you can get suprising results if you mix different argument types in one call:
sum(2.5, 2)returns 4.5 as expected, butsum(2, 2.5)returns 2 because the return type isint, notdouble. If you want to be fancy, you can use the new alternative function syntax to specify that the return type is whatever the natural type ofn + sum(args...)would be:Now
sum(2.5, 2)andsum(2, 2.5)both return 4.5.If your actual logic is more complex than summation, and you don’t want it inlined, you can use the inline template functions to put all the values into some sort of container (such as a
std::vectororstd::array) and pass that into the non-inline function to do the real work at the end.