c++ - 带有 initializer_list 和 size 的 std::unordered_map 构造函数在 main 中编译,但不在类定义中
问题描述
我正在尝试std::unordered_map
使用通过初始化列表和存储桶的初始数量接受数据的构造函数来初始化。
出于某种原因,如果我将构造函数放入,则该构造函数可以工作main
,但是当我将它放入类头时会出现语法错误。
具体来说,标题,称为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);
};
如果我将标题中的定义删除为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(或uniform-initiation)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
}; // >>>
};
推荐阅读
- javascript - 如果键名是变量值,则通过 json 键获取 json 值
- c# - 如果某些消费者无法实现接口方法,我应该让接口方法返回任务吗?
- html - 响应式调整父级内的 HTML div 大小,包括信箱和邮筒,仅 CSS
- ruby-on-rails - Rails 扫描 ActiveRecord 以进行属性更改
- java - JScrollPane 不移动它卡在一个位置
- ruby-on-rails - 如何使用关注点在模型上存储自定义类级数据
- python - OSX Python 2二进制干扰python 3
- scrapy - Scrapy FormRequest 在信用卡登录表单上不起作用
- php - php - 通过页面传递变量并在返回时更改它
- python - 为什么 string.Formatter.format 没有“self”参数?