简体   繁体   English

在std :: unordered_map中使用模板化键

[英]using a templated key in std::unordered_map

I don't understand why my compiler won't accept code below 我不明白为什么我的编译器不接受下面的代码

#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
}

The compiler command is 编译器命令是

clang++ -std=c++14 test.cpp -o test

A compiler error message excerpt is 编译器错误消息摘录是

/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&>()))>

Why isn't it allowed to use typename M<T>::const_iterator as key in std::unordered_map ? 为什么不允许在std::unordered_map使用typename M<T>::const_iterator作为键?

Because the default template argument for hash of std::unordered_map is std::hash , which doesn't provide implementation for iterator. 因为std::unordered_map哈希的默认模板参数是std::hash ,它不提供迭代器的实现。

You need to provide use-defined hash for it, such as 您需要为它提供使用定义的哈希,例如

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
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM