Akmal Sultanov
Akmal Sultanov

Reputation: 13

Initialize your class with constructor which takes std::map as a parameter with brace-enclosed initializer

I have a simple class with constructor which takes std::map. I want to initialize the class with pair of braze-enclosed initializer list. Here's what I've tried:

//X.h
#include <map>

template <class key, class value>
class X{
public:
    X(const std::map<key, value>& map) : m_map{map} {}

private:
    typename std::map<key, value> m_map;
};
//main.C

int main() { 
    std::map<char, int> m = {{'a', 5}};
    X<char, int> x = m; //valid
    X<char, int> y = {{'a', 5}}; // error
}

But I get an error. I guess I have to implement different constructor to be able to initialize with a initializer list but I don't know how.

Upvotes: 1

Views: 283

Answers (1)

r3mus n0x
r3mus n0x

Reputation: 6144

Believe it or not, you are missing another pair of curly braces. This should work:

X<char, int> y = { { {'a', 5 } } };
                 ^ ^ ^~~~~~~~~
                 | | initializes map element
                 | initializes the map
                 initializes your object

Upvotes: 5

Related Questions