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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...