c++ - 带有initializer_list和size的std::unordered_map构造函数在main中编译,但不在类定义中编译

标签 c++ c++11 constructor unordered-map list-initialization

我正在尝试使用通过初始化列表和初始存储桶数量接受数据的构造函数来初始化std::unordered_map

出于某种原因,如果我将其放入 main 中,该构造函数会起作用,但当我将其放入类 header 中时,会出现语法错误。

具体来说, header 名为 momo.h:

#pragma once
#include <unordered_map>

namespace std 
{
   template <>
   struct hash<std::pair<uint16_t, uint16_t>>
   {
      std::size_t operator()(const std::pair<uint16_t, uint16_t>& k) const
      {
         return (std::hash<long>()((((long)k.first) << 16) + (long)k.second));
      }
   };
}

class test
{
   std::unordered_map<std::pair<uint16_t, uint16_t>, uint16_t> m_Z(
      { /* Fails here: syntax error: missing ')' before '{' */
          {std::pair{ 1, 2 }, 3},
          {std::pair{ 4, 5 }, 6}
      }, 128);

};

如果我将定义从 header 删除到 main 中,则:

#include "Momo.h"

int main()
{
   test X;

   std::unordered_map<std::pair<uint16_t, uint16_t>, uint16_t> Y(
      {
          {std::pair{ 1, 2 }, 3},
          {std::pair{ 4, 5 }, 6}
      }, 128);
}

代码编译没有错误。为什么?

最佳答案

您需要braced-init-list (或统一启动)类中的 std::unordered_map

class test
{
   std::unordered_map<std::pair<uint16_t, uint16_t>, uint16_t> m_Z{ // >> brased init
      { 
           {std::pair{ 1, 2 }, 3},
           {std::pair{ 4, 5 }, 6}
      }, 128 
   }; // >>>

};

关于c++ - 带有initializer_list和size的std::unordered_map构造函数在main中编译,但不在类定义中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58577599/

相关文章:

c++ - 为什么我在检查核心转储时进入 gdb "Cannot access memory at address 0x..."?

c++ - 文件夹结构 - 良好做法

c++ - cygwin 中的 SQLite3 导致链接器错误

c++ - 打印实例链

c++ - 类和结构在填充和继承方面的区别

c++11 - 铛。 fatal error : recursive template instantiation exceeded maximum depth

c++ - 为什么这段代码有段错误?

c# - 完全初始化的类

java - 使用多个类时未定义构造函数

c++ - 有条件地禁用复制构造函数