【问题标题】:using a templated key in std::unordered_map在 std::unordered_map 中使用模板键
【发布时间】:2016-05-01 12:53:16
【问题描述】:

我不明白为什么我的编译器不接受下面的代码

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

为什么不允许在std::unordered_map 中使用typename M&lt;T&gt;::const_iterator 作为键?

【问题讨论】:

  • 另外,我不认为那些typenames 是必需的,因为MD 都不是模板参数。

标签: c++ templates c++11 unordered-map


【解决方案1】:

因为std::unordered_map的哈希默认模板参数是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
    }
};

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2012-07-09
    • 1970-01-01
    • 2016-11-15
    • 2018-07-09
    • 1970-01-01
    • 2020-03-09
    • 2011-12-28
    • 1970-01-01
    相关资源
    最近更新 更多