簡體   English   中英

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

為什么不允許在std::unordered_map使用typename M<T>::const_iterator作為鍵?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM