std::unordered_map 具有 initializer_list 和大小的构造函数在 main 中编译,但在 class 定义中不编译
std::unordered_map constructor with initializer_list and size compiles in main, but not in class definition
我正在尝试使用通过初始化列表和初始桶数接受数据的构造函数来初始化 std::unordered_map
。
出于某种原因,如果我将它放在 main
中,该构造函数可以工作,但是当我将它放在 class 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(或统一启动)class 中的 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
}; // >>>
};
我正在尝试使用通过初始化列表和初始桶数接受数据的构造函数来初始化 std::unordered_map
。
出于某种原因,如果我将它放在 main
中,该构造函数可以工作,但是当我将它放在 class 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(或统一启动)class 中的 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
}; // >>>
};