int foo(int i)
{
return i;
}
int foo(int i, int... n)
{
return i + foo(n...);
}
int main()
{
return foo(1, 2, 3); // error
}
Why does C++ not allow such an intuitive syntax?
To access variadic arguments, we must include the <stdarg. h> header.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
A variadic function allows you to accept any arbitrary number of arguments in a function.
A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called.
You need the template mechanism to instantiate your second foo
function, since the signature of the function is only determined when it's used. So the only feature you could ask for here, is that your syntax implies a function template where the template parameter pack is constrained to type int
.
There is considerable opposition to templates that don't have the template keyword, though. However, things will change in that regard with the Concepts TS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With