用户定义类的哈希函数.如何交朋友?:).

Hash function for user defined class. How to make friends? :)

本文关键字:交朋友 函数 定义 哈希 用户      更新时间:2023-10-16

我有一个C类,它有一个string* ps私有数据成员。
现在,我想要一个需要自定义哈希函数的unordered_map<C, int>

根据 c++ 参考,我可以这样做

namespace std {
  template<>
  class hash<C> {
  public:
    size_t operator()(const C &c) const
    {
      return std::hash<std::string>()(*c.ps);
    }
  };
}

问题是我似乎无法结交operator()C朋友,以便我可以访问ps

我试过这个:

class C;
template<>
class std::hash<C>;
class C{
  //...
  friend std::hash<C>::operator ()(const C&) const; // error: Incomplete type 
};
// define hash<C> here.

但它说不完整的类型...在嵌套名称说明符中...

我也无法扭转定义,因为如果以后定义 C 类,hash<C>就无法了解ps

我在这里做错了什么?如何在不公开的情况下解决这种情况ps

试试这个:

class C;
namespace std {
  template<>
  struct hash<C> {
  public:
    size_t operator()(const C &c) const; // don't define yet
  };
}
class C{
  //...
  friend size_t std::hash<C>::operator ()(const C&) const;
};
namespace std {
  template<>
  size_t hash<C>::operator()(const C &c) const {
    return std::hash<std::string>()(*c.ps);
  }
}

或者这个:

class C;
template<>
struct std::hash<C>;
class C{
  friend struct std::hash<C>; // friend the class, not the member function
};

(我还没有编译,所以可能有语法错误)

更简单的交友方式:

class C {
  template <typename T> friend class std::hash;
};

即使 C 位于自己的命名空间中或是一个嵌套类,这也有效,因为 std::hash 不必向前声明。

我建议添加如下方法

class C
{
....
public:  const string* get_ps() const { return ps; }
....
};

并将其用于哈希专用化。