Uri*_*Raz 4 c++ constructor unordered-map c++11 list-initialization
我正在尝试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);
};
Run Code Online (Sandbox Code Playgroud)
而如果我将标头中的定义删除为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);
}
Run Code Online (Sandbox Code Playgroud)
该代码编译没有错误。为什么?
您需要在类中 括号初始化列表(或统一初始化)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
}; // >>>
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |