参数包函数参数是否可以默认? [英] Can parameter pack function arguments be defaulted?
问题描述
这是一个点,gcc 4.9.2和clang 3.5.2是在锋利的
不同意。程序:
template< typename ... Ts>
int foo(int i = 0,Ts& ... args)
{
return i + sizeof ...(Ts);
}
int main()
{
return foo();
}
编译没有gcc( -std = c ++ 11 -Wall -pedantic
)。 Clang说:
错误:参数'args'缺少默认参数
pre>
foo
修改为:template< typename ... Ts>
int foo(int i = 0,Ts& ... args = 0)
{
return i + sizeof ...(Ts);
}
clang没有投诉,但gcc表示:
错误:参数包'args'不能有默认参数
哪个编译器是正确的?
解决方案从8.3.6([dcl.fct.default] )/ 3:
不应为参数包指定默认参数。
从8.3.6([dcl.fct.default])/ 4:
一个给定的函数声明,带有默认参数的参数后面的每个参数应该有一个在这个或前面的声明中提供的默认参数,或者是一个函数参数包。
所以这允许像
void f(int a = 10,Args ... args)
这样的代码,或者像你的第一个代码片段。 (感谢@ T.C。查找第二句话!)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?
解决方案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!)这篇关于参数包函数参数是否可以默认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!