如何使用列表初始化来初始化 `std::map<std::string, CodeInfo>`?

How to initialize the `std::map<std::string, CodeInfo>` using list-initialization?

我有一个带有 string 键和 struct 值的映射,我不知道为什么我不能实例化一个对象a list of initializers:

#include <string>
#include <map>    
using namespace std;

struct CodeInfo
{
    int _level = 0;
    bool _reactive;
};
typedef map<string, CodeInfo> CodeInfos; // Key is code name

int main()
{
    CodeInfos codes = { {"BARECODE", { 0, true }}, {"BARECODE2", { 0, false }} };

    return 0;
}

看起来很简单,但我不明白为什么会出现以下错误:

In function 'int main()':    
24:80: error: could not convert '{{"BARECODE", {0, true}}, {"BARECODE2", {0, false}}}' from '<brace-enclosed initializer list>' to 'CodeInfos {aka std::map<std::basic_string<char>, CodeInfo>}'

我在 C++11 中使用编译器 g++ (GCC) 4.9.1 20140922 (Red Hat 4.9.1-10)。

原因是 CodeInfo 不是聚合,因为您在 class.

的定义中直接初始化其中一个数据成员 (_level = 0)

删除 default initialization of that member will work with C++11. See here

阅读此 post 了解有关聚合的更多信息:What are Aggregates and PODs and how/why are they special?