Building std :: map from error initializer_list

I am trying to create a constructor for a class that takes a list of initializers and starts a map with it as follows:

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

But this leads to a very long error message, which I frankly do not understand. What do I need to change to make this work?

+4
source share
1 answer

Declare the template argument std::initializer_listas being of typestd::pair<const int, int>

Here is a demo program

#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 as follows

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

and value_type is defined as

typedef pair<const Key, T> value_type;

So you can define the constructor of your class as follows

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

Source: https://habr.com/ru/post/1570748/


All Articles