Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ not allow variadic parameters in a non-template function?

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?

like image 245
xmllmx Avatar asked Dec 13 '16 11:12

xmllmx


People also ask

How do you access variadic arguments?

To access variadic arguments, we must include the <stdarg. h> header.

What is variadic function in C?

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.

Can variadic methods take any number of parameters?

A variadic function allows you to accept any arbitrary number of arguments in a function.

Why do we use variadic parameters in Swift?

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.


1 Answers

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.

like image 89
Vir Avatar answered Oct 23 '22 06:10

Vir