加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 通过make_unique / make_shared调用initializer_list构造函

发布时间:2020-12-16 05:30:50 所属栏目:百科 来源:网络整理
导读:我试图使用std :: make_unique来实现一个构造函数接收std :: initializer_list的类.这里有一个最小的例子: #include string#include vector#include initializer_list#include memorystruct Foo { Foo(std::initializer_liststd::string strings) : strings
我试图使用std :: make_unique来实现一个构造函数接收std :: initializer_list的类.这里有一个最小的例子:
#include <string>
#include <vector>
#include <initializer_list>
#include <memory>

struct Foo {
    Foo(std::initializer_list<std::string> strings) : strings(strings) {}

    std::vector<std::string> strings;
};

int main(int,char**) {

    auto ptr = std::make_unique<Foo>({"Hello","World"});

    return 0;
}

您可以在Coliru看到它没有构建:

main.cpp:14:56: error: no matching function for call to 'make_unique(<brace-enclosed initializer list>)'
     auto ptr = std::make_unique<Foo>({"Hello","World"});

那么,据说make_unique无法使用initializer_lists? GCC 4.9.1中有错误吗?还是我忽略了一些东西?

解决方法

std :: make_unique是推导传递给对象构造函数的参数类型的函数模板.不幸的是,支持列表不可推导(自动声明有异常),因此当缺少参数类型时,无法实例化函数模板.

你可以不使用std :: make_unique,但请不要去那条路线 – 你应该尽可能多地避免赤裸裸的消息,为了孩子们的缘故.或者您可以通过指定类型来进行类型扣除:

> std :: make_unique< Foo>(std :: initializer_list< std :: string>({“Hello”,“World”}))
> std :: make_unique< Foo,std :: initializer_list< std :: string>>({“Hello”,“World”})
> auto il = {“你好”,“世界”}; auto ptr = std :: make_unique< Foo>(il);

最后一个选项使用自动声明的特殊规则,(正如我上面提到的)实际上推导了一个std :: initializer_list.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读