我正在尝试使用通过初始化列表接受数据的构造函数和存储桶的初始数量来初始化std::unordered_map
。
出于某种原因,如果我将其放在main
中,则该构造函数会起作用,但是当我将其放入class
标头中时,会出现语法错误。
特别是标题,称为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); }
代码编译无误。为什么?
我正在尝试使用构造函数来初始化std :: unordered_map,该构造函数通过初始化列表和初始存储桶数量接受数据。出于某种原因,如果我...
您需要在类中将braced-init-list std::unordered_map
(或统一初始化)。