Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can parameter pack function arguments be defaulted?

This is a point about which gcc 4.9.2 and clang 3.5.2 are in sharp disagreement. The program:

template<typename ...Ts> int foo(int i = 0, Ts &&... args) {     return i + sizeof...(Ts); }  int main() {     return foo(); } 

compiles without comment from gcc (-std=c++11 -Wall -pedantic). Clang says:

error: missing default argument on parameter 'args' 

With foo amended to:

template<typename ...Ts> int foo(int i = 0, Ts &&... args = 0) {     return i + sizeof...(Ts); } 

clang has no complaints, but gcc says:

error: parameter pack ‘args’ cannot have a default argument 

Which compiler is right?

like image 269
Mike Kinghan Avatar asked Mar 17 '15 12:03

Mike Kinghan


People also ask

Can all the parameters of a function can be default parameters?

D. No parameter of a function can be default.

Can parameters have default values?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

Which function Cannot have a default argument?

Constructors cannot have default parameters.

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.


2 Answers

From 8.3.6 ([dcl.fct.default])/3:

A default argument shall not be specified for a parameter pack.

From 8.3.6 ([dcl.fct.default])/4:

In a given function declaration, each parameter subsequent to a parameter with a default argument shall have a default argument supplied in this or a previous declaration or shall be a function parameter pack.

So this allows code like void f(int a = 10, Args ... args), or indeed like your first snippet. (Thanks to @T.C. for looking up the second sentence!)

like image 180
Kerrek SB Avatar answered Sep 24 '22 17:09

Kerrek SB


A Kerrek SB says, it's not possible. What you could do, instead, is using a std::tuple

template <class ... Args> void foo( std::tuple<Args...> t = std::tuple<int>(0) ) {} 
like image 40
edmz Avatar answered Sep 22 '22 17:09

edmz