Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...