[英]How to use variants as the key in 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::remove_const_t<Types>>...
每个特化都被启用,则特化std::hash<std::variant<Types...>>
被启用(见 std::hash),否则被禁用。
但是您的所有变体类型都有默认散列,因此,对于您的变体类型,它在没有第三个参数的情况下编译,因为标准散列有效。 但是,如果您的变体中有一个没有散列函数(或 == 运算符)的类型,那么它将无法编译并出现以下错误:
错误:静态断言失败:必须使用键类型的参数调用散列函数
所以回到你的问题:
当变体类型具有哈希函数时:
#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
...
你可以在这里自己尝试:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.