vendredi 16 novembre 2018

std::hash specialisation forwn my own class and use it inside the class

I define a class Foo, and would like to have a public member function that takes std::unordered_set<Foo> as parameters type.

To be able to use std::unordered_set<Foo>, I have to specialize std::hash<Foo> in namespace std.

That's ok if I do not try to use std::unordered_set<Foo> as paramter type in Foo member functions.

However, once I want to use std::unordered_set<Foo> as parameter type in Foo member functions, I Have a problem to define the specialization std::hash<Foo>. If I do it after the Foo declaration, there is an error on Foo declaration because std::hash<Foo> is not defined. It a move std::hash<Foo> definition before, it does not work either because now Foo is unknown. Forward declaration of Foodoes not work in such situation.

Any ideas how to resolve this ?

Here is an example of such a class

class Foo
{
public:
  std::unordered_set<Foo>::iterator findClosest(std::unordered_set<Foo> const &others)
  {
    return std::end(others);
  }

  size_t hashValue() const {
    return std::hash<int>()(m_Member);
  }

private:
  int m_Member;
};

namespace std
{
  template <>
  struct hash<Foo>
  {
    size_t operator()(Foo const & bar) const
    {
      return bar.hashValue();
    }
  };
}

Aucun commentaire:

Enregistrer un commentaire