gpt4 book ai didi

c++ - 为什么 std::make_unique 等不存在 std::initializer_list 重载?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:12 24 4
gpt4 key购买 nike

参见 Should I use () or {} when forwarding arguments? . foostd::vector克隆。

在 N4140 中,unique.ptr.create std::make_unique指定为:

template <class T, class... Args> unique_ptr<T> make_unique(Args&&... args);

  • Remarks: This function shall not participate in overload resolution unless T is not an array.

  • Returns: unique_ptr<T>(new T(std::forward<Args>(args)...)).

这意味着需要实现才能使用 ()而不是 {}来初始化对象。举个例子,下面的

auto s1 = std::make_unique<foo>(3, 1).get()->size();
auto s2 = std::make_unique<foo>(1).get()->size();
auto s3 = std::make_unique<foo>(2).get()->size();
std::cout << s1 << s2 << s3;

输出 312而如果 {} (在 std::make_unique 内)使用了 211将被输出。因为无法推导出初始化列表,std::initializer_list必须显式传递才能获得后一个结果。问题是,为什么不提供这样的重载?

namespace test
{

template <class T, class Deduce>
std::unique_ptr<T> make_unique(std::initializer_list<Deduce> li)
{
return ::std::make_unique<T>(li);
}

};

int main()
{
auto p1 = test::make_unique<foo>({3, 1}).get()->size();
auto p2 = test::make_unique<foo>({1}).get()->size();
auto p3 = test::make_unique<foo>({2}).get()->size();
std::cout << p1 << p2 << p3;
}

输出 211 .

我不认为“您可以自己编写”或“避免使标准膨胀”是很好的理由。提供这种重载有什么缺点吗?

最佳答案

我不知道完整的历史,但最有可能的答案是“没有人提出过”。

std::make_unique 仅在 C++14 中添加,而 std::unique_ptr 存在于 C++11 中这一事实支持了这一点.

std::make_shared 的代码和提案(最终反射(reflect)在 make_unique 中)在 initializer_list 之前就已存在(在 boost 中)以及支持它的初始化语法。

你现在可以做的一件事是提出它(并解决极端情况,如果有的话,例如,如果目标类型不支持 initializer_list,则使用 SFINAE 删除重载).

关于c++ - 为什么 std::make_unique 等不存在 std::initializer_list 重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37160587/

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