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

X''*_*X'' 13 c++ hash unordered-map c++11

我有一个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);
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

问题是,我似乎无法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.
Run Code Online (Sandbox Code Playgroud)

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

我也无法扭转这些定义,因为如果后来定义了C类,hash<C>则无法知道ps.

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

Pub*_*bby 17

试试这个:

class C;
namespace std {
  template<>
  struct hash<C> {
  public:
    size_t operator()(const C &c) const; // don't define yet
  };
}
class C{
  //...
  friend 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

或这个:

class C;
template<>
struct std::hash<C>;
class C{
  friend struct std::hash<C>; // friend the class, not the member function
};
Run Code Online (Sandbox Code Playgroud)

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

  • 对于msvc2012,你需要在size_t`hash <C> :: operator()`的实现中删除`template <>`,否则`错误C2910不能显式专门化.` (3认同)