在 std::unordered_map 中使用模板化键
using a templated key in std::unordered_map
我不明白为什么我的编译器不接受下面的代码
#include <unordered_set>
#include <unordered_map>
template<class T>
using M = std::unordered_set<T>;
template<class T>
using D = M<T>;
template<class T>
using DM = std::unordered_map < typename M<T>::const_iterator // Problem
, typename D<T>::const_iterator >; // Problem
int main(int argc, char ** argv)
{
D<int> d;
M<int> m;
DM<int> dm; // Problem
}
编译命令为
clang++ -std=c++14 test.cpp -o test
编译器错误消息摘录为
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.1/../../../../include/c++/5.3.1/bits/hashtable_policy.h:85:11: error:
implicit instantiation of undefined template
'std::hash<std::__detail::_Node_const_iterator<int, true, false> >'
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
为什么不允许使用 typename M<T>::const_iterator
作为 std::unordered_map
中的键?
因为 std::unordered_map
is std::hash
的散列的默认模板参数不提供迭代器的实现。
您需要为其提供自定义哈希值,例如
struct iterator_hash {
template <typename I>
std::size_t operator()(const I &i) const {
return std::hash<int>()(*i); // or return sth based on i
}
};
我不明白为什么我的编译器不接受下面的代码
#include <unordered_set>
#include <unordered_map>
template<class T>
using M = std::unordered_set<T>;
template<class T>
using D = M<T>;
template<class T>
using DM = std::unordered_map < typename M<T>::const_iterator // Problem
, typename D<T>::const_iterator >; // Problem
int main(int argc, char ** argv)
{
D<int> d;
M<int> m;
DM<int> dm; // Problem
}
编译命令为
clang++ -std=c++14 test.cpp -o test
编译器错误消息摘录为
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.1/../../../../include/c++/5.3.1/bits/hashtable_policy.h:85:11: error:
implicit instantiation of undefined template
'std::hash<std::__detail::_Node_const_iterator<int, true, false> >'
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
为什么不允许使用 typename M<T>::const_iterator
作为 std::unordered_map
中的键?
因为 std::unordered_map
is std::hash
的散列的默认模板参数不提供迭代器的实现。
您需要为其提供自定义哈希值,例如
struct iterator_hash {
template <typename I>
std::size_t operator()(const I &i) const {
return std::hash<int>()(*i); // or return sth based on i
}
};