gpt4 book ai didi

c++ - 为什么默认参数后允许使用参数包?

转载 作者:IT老高 更新时间:2023-10-28 21:55:07 26 4
gpt4 key购买 nike

也许我遗漏了一些明显的东西,但是下面的编译和运行,我不知道为什么。我知道 this ,但在下面的示例中,参数包的位置和默认参数是相反的。它不违反默认参数必须出现在最后的规则吗?参数包不能有默认值。

#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
int i;
std::string str;

Test(int _i = 0, Ts&& ... _ts)
:
i(_i),
str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
{}
};

int main()
{
Test<std::string> t(1, "huh??");
std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

return 0;
}

这会产生

t.i = 1, t.str = huh??

最佳答案

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

For non-template functions, default arguments can be added in later declarations of a function in the same scope. Declarations in different scopes have completely distinct sets of default arguments. That is, declarations in inner scopes do not acquire default arguments from declarations in outer scopes, and vice versa. 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. A default argument shall not be redefined by a later declaration (not even to the same value). [ Example:

void g(int = 0, ...); // OK, ellipsis is not a parameter. So it can follow a parameter with a default argument

关于c++ - 为什么默认参数后允许使用参数包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47330640/

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