从 initializer_list 错误构造 std::map

我正在尝试创建一个类构造函数,它将采用一个初始化列表并使用它初始化一个映射,如下所示:

I'm trying to make a class constructor that will take an initializer list and init a map with it like this:

class Test {
    std::map<int, int> m_ints;
public:
    Test(std::initializer_list<std::pair<int, int>> init):
        m_ints(init)
    {}
};

但这会导致很长的错误消息,坦率地说我不明白.我需要进行哪些更改才能完成这项工作?

But that results in a very long error message which I frankly don't understand. What do I need to change to make this work?

推荐答案

std::initializer_list 的模板参数声明为具有类型 std::pair;

Declare the template argument of the std::initializer_list as having type std::pair<const int, int>

这是一个演示程序

#include <iostream>
#include <map>
#include <initializer_list>

class Test {
    std::map<int, int> m_ints;
public:
    Test(std::initializer_list<std::pair<const int, int>> init):
        m_ints(init)
    {}
};

int main()
{
    Test t = { { 1, 2 }, { 2, 3 } };

    return 0;
}

对应的构造函数声明如下

The corresponding constructor is declared the following way

map( initializer_list<value_type>,
     const Compare& = Compare(),
     const Allocator& = Allocator());

而 value_type 的定义类似于

and value_type is defined like

typedef pair<const Key, T> value_type;

因此,您也可以通过以下方式定义类的构造函数

Thus you could define the constructor of your class also the following way

Test( std::initializer_list<std::map<int, int>::value_type> init ) :
      m_ints(init)
{}

相关文章