通过make_unique / make_shared调用initializer_list构造函数 [英] Calling initializer_list constructor via make_unique/make_shared
问题描述
我试图使用 std :: make_unique
来构造一个类,其构造函数是接收 std :: initializer_list
。这里有一个小例子:
I'm trying to use std::make_unique
to instanciate a class whose constructor is to receive an std::initializer_list
. Here a minimal case :
#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_list
s? GCC 4.9.1中是否有错误?还是我忽略了某些东西?
So, is make_unique
reportedly unable to use initializer_list
s ? Is there a bug in GCC 4.9.1 ? Or did I overlook something ?
推荐答案
std :: make_unique
函数模板,它推导出传递给对象构造函数的参数类型。不幸的是,支撑列表是不可推导的(除了 auto
声明),所以你不能在缺少参数类型时实例化函数模板。
std::make_unique
is a function template which deduces the argument types which are passed to the object constructor. Unfortunately, braced lists are not deducible (with an exception for auto
declarations), and so you cannot instantiate the function template when that missing parameter type.
你可以不使用 std :: make_unique
,但请不要走那条路线–你应该尽可能地避免裸体新
,为孩子们的缘故。或者您可以通过指定类型来进行类型推导工作:
You can either not use std::make_unique
, but please don't go that route – you should avoid naked new
s as much as you can, for the children's sake. Or you can make the type deduction work by specifying the type:
-
std :: make_unique< Foo> ;(std :: initializer_list< std :: string>({Hello,World}))
code> std :: make_unique< Foo,std :: initializer_list< std :: string>>({Hello,World})
std::make_unique<Foo, std::initializer_list<std::string>>({"Hello", "World"})
auto il = {Hellos,Worlds}; auto ptr = std :: make_unique< Foo>(il);
选项使用 auto
声明的特殊规则(如上面的暗示) 实际上推导出 std :: initializer_list
。
The last option uses the special rule for auto
declarations, which (as I hinted above) do in fact deduce an std::initializer_list
.
这篇关于通过make_unique / make_shared调用initializer_list构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!