在初始化列表中初始化 unordered_map

Initialize unordered_map in the initializer list

我正试图找到一个可能非常微不足道的问题的解决方案。我想在 class 初始化列表中初始化我的 const unordered_map。但是我还没有找到编译器 (GCC 6.2.0) 将接受的语法。代码 link 是 here.

#include <unordered_map>

class test {
 public:
    test()
      : map_({23, 1345}, {43, -8745}) {}

 private:
   const std::unordered_map<long, long> map_;
 };

错误:

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}) {}
                                ^

是否不允许在初始化列表中初始化复数常量?或者语法必须不同?

使用大括号代替圆括号

class test {
 public:
    test()
      : map_{{23, 1345}, {43, -8745}} {}

 private:
   const std::unordered_map<long, long> map_;
 };

使用大括号而不是圆括号,因为如果使用圆括号,它会调用最匹配参数的构造函数,而不是使用 initializer_list.

类型参数的重载构造函数

使用圆括号和大括号具有相同的效果,直到有一个重载的构造函数将 initializer_list 类型作为参数。然后,当您使用大括号时,编译器将竭尽全力尝试调用重载的构造函数。

例如:

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.