Reputation: 4938
I'm trying to find a solution to what may be a very trivial problem. I would like to initialize my const unordered_map
in the class initializer list. However I'm yet to find the syntax that the compiler (GCC 6.2.0) will accept. A code link is here.
#include <unordered_map>
class test {
public:
test()
: map_({23, 1345}, {43, -8745}) {}
private:
const std::unordered_map<long, long> map_;
};
Error:
main.cpp: In constructor 'test::test()':
main.cpp:6:36: error: no matching function for call to 'std::unordered_map<long int, long int>::unordered_map(<brace-enclosed initializer list>, <brace-enclosed initializer list>)'
: map_({23, 1345}, {43, -8745}) {}
^
Are the complex constants not allowed to be initialized in the initializer list? Or the syntax has to be different?
Upvotes: 9
Views: 30840
Reputation: 31
Use curly braces instead of the parentheses because if you use parentheses it's calling the constructor that best matches your arguments instead of the overloaded constructor with a parameter of type initializer_list.
Using parentheses and curly braces have the same effect until there's an overloaded constructor taking initializer_list type as a parameter. Then when you use curly braces, the compiler is going to bend over backwards to try to call that overloaded constructor.
for example:
Foo( 3 ) is calling Foo( int x ) constructor;
Foo{ 3 } is calling Foo( initializer_list<int> x ) constructor;
but if there's no Foo( initializer_list<int> x ) constructor
then Foo( 3 ) and Foo{ 3 } are both calling Foo( int x ) constructor.
Upvotes: 3
Reputation: 310990
Use braces instead of the parentheses
class test {
public:
test()
: map_{{23, 1345}, {43, -8745}} {}
private:
const std::unordered_map<long, long> map_;
};
Upvotes: 16