用户定义的类的散列函数。 如何交朋友? :)(Hash function for user d

2019-07-05 09:00发布

I have a class C, which has a string* ps private data member.
Now, I'd like to have an unordered_map<C, int> for which I need a custom hash function.

According to the c++ reference, I can do that like

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

The problem is that I can't seem to make operator() and C friends so that I could access ps.

I have tried this:

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

but it says that Incomplete type ... in nested name specifier ...

I can't turn around the definitions either, because if class C is defined later, the hash<C> has no way to know about ps.

What am I doing wrong here? How can this situation be fixed without making ps public?

Answer 1:

试试这个:

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);
  }
}

或这个:

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

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



Answer 2:

我建议添加方法如下一样

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

而在你的哈希专业化使用它。



文章来源: Hash function for user defined class. How to make friends? :)