微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我试图使用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.

原文地址:https://www.jb51.cc/c/114553.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐