gpt4 book ai didi

c++ - 初始化列表中的对象初始化问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:54 25 4
gpt4 key购买 nike

我有以下代码:

    class A {
public:
A(std::vector<std::shared_ptr<int>>){}
};

auto x = std::make_shared<int>(0);
auto y = std::make_shared<int>(1);

auto list = {x, y};
auto res = std::make_shared<A>({x, y});

在这个例子中,如果我传递给 res 变量列表,它会编译,否则就像直接使用初始化列表一样,它会失败 http://ideone.com/8jYsDY

我想这与涉及 initializer_list 时类型推导的工作方式有关。如果这是符合标准的,那么一些引用资料会很好。

最佳答案

std::make_shared 从函数调用的参数中推导出它的第二个模板参数。 braced-init-list 不是表达式,因此没有类型。因此,模板参数推导不能从中推导出类型。

来自 §14.8.2.5/5 [temp.deduct.type]

The non-deduced contexts are:
  — ...
  — A function parameter for which the associated argument is an initializer list (8.5.4) but the parameter does not have std::initializer_list or reference to possibly cv-qualified std::initializer_list type. [ Example:

 template<class T> void g(T);
g({1,2,3}); // error: no argument deduced for T

—end example ]

auto , 然而, 是一个允许推断的特例 std::initializer_list<T>来自花括号初始化列表。

§7.1.6.4/7 [dcl.spec.auto]

... Otherwise, obtain P from T by replacing the occurrences of auto with either a new invented type template parameter U or, if the initializer is a braced-init-list, with std::initializer_list<U>. Deduce a value for U using the rules of template argument deduction from a function call (14.8.2.1), where P is a function template parameter type and the initializer is the corresponding argument. If the deduction fails, the declaration is ill-formed. Otherwise, the type deduced for the variable or return type is obtained by substituting the deduced U into P. [ Example:

 auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
auto x2 = { 1, 2.0 }; // error: cannot deduce element type

—end example ]

在您的示例中,变量 list类型为 initializer_list<shared_ptr<int>> , 当你把它传递给 make_shared , 一个 vector可以从中构建,然后用于直接初始化 A实例。

其他选项是构造一个 vector

auto res = std::make_shared<A>(std::vector<std::shared_ptr<int>>{x, y});

构造一个 A ,然后将被移动

auto res = std::make_shared<A>(A{{x, y}});

或为 make_shared 指定模板参数明确地

auto res = std::make_shared<A, std::initializer_list<std::shared_ptr<int>>>({x, y});

关于c++ - 初始化列表中的对象初始化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25179414/

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