gpt4 book ai didi

c++ - 列表初始化器和可变参数构造函数

转载 作者:太空狗 更新时间:2023-10-29 20:37:44 24 4
gpt4 key购买 nike

来自 CPP reference关于列表初始化:

Otherwise, the constructors of T are considered, in two phases:

  • All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list

  • If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all)

所以构造函数使用 initializer_list被首先考虑。如果做不到这一点,列表中的每个元素都被视为构造函数的参数。然而

#include <iostream>

using namespace std;

struct A{
template <typename... Args> A(Args... li) { cout << sizeof...(Args) << endl;}
};

int main(){

A a = {2,3,4};

}

输出是3这表明 Args...解压为 int, int, int .为什么 Args... 不是简单地成为单数 initializer_list<int> , 列表初始化的详细信息表明哪些是构造函数的第一个尝试类型?

最佳答案

[temp.deduct.call]/1 Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below. If removing references and cv-qualifiers from P gives std::initializer_list<P'> for some P' and the argument is an initializer list (8.5.4), then deduction is performed instead for each element of the initializer list, taking P' as a function template parameter type and the initializer element as its argument. Otherwise, an initializer list argument causes the parameter to be considered a non-deduced context (14.8.2.5).

强调我的。出于这个原因,构造函数的模板参数从 initializer_list<int> 类型的参数中推导。失败。

关于c++ - 列表初始化器和可变参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948090/

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