为嵌套自定义类型定义散列函数

defining hash function for nested custom type

本文关键字:定义 散列函数 类型 自定义 嵌套      更新时间:2023-10-16

给定如下嵌套模板类结构:

template<class T> class A
{
  ...
public:
  ...
  class B;
};

我希望std::哈希函数在嵌套类上工作,这样它就可以放在unsorted_map和unsorted_set中,所以我将嵌套类定义为:

template<class T> class A<T>::B 
{
  public:
    bool operator==(const A<T>::B &) const;
  ...
  friend struct std::hash<A<T>::B>;
};

然后尝试为该类型添加一个特殊的std::散列结构,如下所示:

namespace std
{
  template<class T> struct hash<A<T>::B>
  {
    bool operator()(const A<T>::B &x) const
    {
       ...
    }
  };
}

但是当我尝试像这样定义自定义std::hash函数对象时,编译器会强烈地抱怨。

我得到的错误信息是无用的,如下所示:

xyz.cc:17:38: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Tp> struct std::hash'
 template<class T> struct hash<A<T>::B>
                                      ^
xyz.cc:17:38: error:   expected a type, got 'A<T>::B'

我不确定我应该如何表达它,然而。

为什么这是错误的,我必须做什么来修复它?

你不能。

依赖类型不能进行模式匹配,因为一般情况下需要反转任意的图灵完全算法。

最简单的方法是使B成为一个独立的模板,然后将pedef类型化为A