[英]Build fails for unordered_map with pair as a key (C++)
我看到有可能使用std::pair
作為std::unordered_map
的鍵。 在我的情況下,我需要在對中使用std::type_index
。 但是在構建它時遇到一些問題。 我的代碼是:
template<class Base, class Result, bool Commutative>
struct Multimethod2
{
using Args = std::pair<std::type_index, std::type_index>;
using Method = std::function<bool(Base *, Base *)>;
struct ArgsHash {
std::size_t operator () (Args &p) const {
std::size_t h1 = std::hash<std::type_index>()(p.first);
std::size_t h2 = std::hash<std::type_index>()(p.second);
return h1 ^ h2;
}
};
struct KeyEqual
{
bool operator()(const Args &a1, const Args &a2) const
{
return (a1.first == a2.first && a1.second == a2.second) ||
(a1.first == a2.second && a1.second == a2.first);
}
};
std::unordered_map<Args, Method, ArgsHash, KeyEqual> methods;
...
}
得到錯誤:
/usr/include/c++/7/bits/hashtable_policy.h:87: error: no match for call to ‘(const Multimethod2<Shape, bool, true>::ArgsHash) (const std::pair<std::type_index, std::type_index>&)’
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/7/bits/hashtable_policy.h:87: error: binding reference of type ‘Multimethod2<Shape, bool, true>::Args& {aka std::pair<std::type_index, std::type_index>&}’ to ‘const std::pair<std::type_index, std::type_index>’ discards qualifiers
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/7/type_traits:154: error: ‘value’ is not a member of ‘std::__and_<std::__is_fast_hash<Multimethod2<Shape, bool, true>::ArgsHash>, std::__detail::__is_noexcept_hash<std::pair<std::type_index, std::type_index>, Multimethod2<Shape, bool, true>::ArgsHash> >’
: public integral_constant<bool, !_Pp::value>
^~~~
...
這里的語法有什么問題?
根據哈希要求, ArgsHash::operator()
應該通過const&
獲取Args
。
順便說一下,你的哈希函數可能很糟糕(當你有兩個相同的type_index時會發生什么?)
組合哈希並不是微不足道的(有一個原因就是沒有std :: hash_combine); 無論如何,您可能想嘗試使用boost.hash_combine來制作一個現成的或多或少的通用解決方案......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.