gpt4 book ai didi

c++ - 参数包函数参数可以默认吗?

转载 作者:IT老高 更新时间:2023-10-28 13:01:14 31 4
gpt4 key购买 nike

这是 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 说:

error: missing default argument on parameter 'args'

foo修改为:

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

clang 没有提示,但 gcc 说:

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

哪个编译器是正确的?

最佳答案

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

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

从 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.

所以这允许像 void f(int a = 10, Args ... args) 这样的代码,或者确实像你的第一个片段。 (感谢@T.C. 查找第二句话!)

关于c++ - 参数包函数参数可以默认吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098835/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com