我正在尝试使用通过初始化列表和初始存储桶数量接受数据的构造函数来初始化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/