c++ - 如何使用变体作为 unordered_map 中的键?
问题描述
如何使用变体作为 unordered_map 中的键?
例如,我想让下面的代码工作。
using VariantType = std::variant<int, std::string, unsigned int>;
std::unordered_map<VariantType, int, $some_hash_function$> m;
如何实现 $some_hash_function$?
解决方案
已经有一个针对变体的哈希模板特化:
http://en.cppreference.com/w/cpp/utility/variant/hash
唯一的条件是变体中的每个类型都必须有一个哈希函数:
如果启用了每个特
std::hash<std::variant<Types...>>
化,则启用特化(参见 std::hash)std::hash<std::remove_const_t<Types>>...
,否则禁用。
但是您的所有变体类型都有默认哈希,因此对于您的变体类型,它在没有第三个参数的情况下编译,因为标准哈希有效。但是,如果您的变体中有一个没有散列函数(或 == 运算符)的类型,那么它将无法编译并出现以下错误:
错误:静态断言失败:哈希函数必须可以使用键类型的参数调用
所以回到你的问题:
当变体类型具有哈希函数时:
#include <variant>
#include <unordered_map>
#include <string>
#include <iostream>
using VariantType = std::variant<int, std::string, unsigned int>;
std::unordered_map<VariantType, int> m =
{
{1, 1},
{2u, 2},
{std::string("string"),3}
};
int main()
{
VariantType v = std::string{"string"};
std::cout << m[v];
}
你得到这个输出:
Program returned: 0
Program stdout
3
当并非所有变体类型都具有哈希函数时:
#include <variant>
#include <unordered_map>
#include <string>
#include <iostream>
class UnhashedClass {};
using VariantType = std::variant<UnhashedClass, int, std::string>;
std::unordered_map<VariantType, int> m =
{
{1, 1},
{2u, 2},
{std::string("string"),3}
};
int main()
{
VariantType v = std::string{"string"};
std::cout << m[v];
}
你得到这个输出:
Could not execute the program
Compiler returned: 1
Compiler stderr
...
error: static assertion failed: hash function must be invocable with an argument of key type
...
您可以在这里自己尝试:
推荐阅读
- java - How let loop of buttons comunicate to each other
- c# - How can I save a captured picture from the user to the cosmos db in xamarin forms?
- reactjs - 即使在重新加载选项后,下拉列表的选定值仍然存在
- sql - SQL 在一段时间后重新初始化值
- reactjs - React slick doesn't loop slides if slidesToShow is equal to the total slides
- php - SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens...but it does?
- ios - How can I debug EXC_BAD_ACC (code=2, address=xxx)?
- android - Android menu icon size, i dont know how to change it
- sql - 当我加入最终表时数据消失 - SQL
- neo4j - Neo4j 嵌套 XML 文件加载