[英]Initialize a container inside a class/struct with std::initializer_list
I never was really able to work with std::initializer_list
, and I'd like to change that. 我从来没有真正能够使用
std::initializer_list
,我想更改它。 So I'm trying to do this really simple thing, which is to forward the initializer list to initialize a struct member. 因此,我正在尝试做一件非常简单的事情,即转发初始化程序列表以初始化struct成员。 I tried a lot of things, but there is a example :
我尝试了很多事情,但是有一个例子:
#include <unordered_map>
#include <functional>
struct Foo
{
using U_Func = std::function<void()>;
using U_MapFunc = std::unordered_map<std::string, U_Func>;
U_MapFunc funcMap;
Foo(std::initializer_list<U_MapFunc::value_type> mapParams)
: funcMap(mapParams)
{}
};
Foo test(
{"", []() {}}
);
Someone can tell me how I should write this code? 有人可以告诉我如何编写此代码?
This is basically not much more than a typo. 基本上,这只是错字。
You only provided one value_type
in the initializer_list, but it is supposed to be, well, a list of value_type
s. 您只在initializer_list中提供了一个
value_type
,但应该是value_type
的列表 。 So, add another set of braces: 因此,添加另一组花括号:
Foo test(
{{"", []() {}}}
);
Or write it like this for added clarity: 或这样写,以提高清晰度:
Foo test{
// Element list under here
{
// One element here
{"", []() {}}
}
};
The resulting std::initializer_list
can be copied (though the things inside it won't be copied) so your "forwarding" works just fine. 可以复制生成的
std::initializer_list
(尽管其中的内容不会被复制),因此您的“转发”效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.