Reputation: 13
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
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