std:hash 可以访问 class 的私有成员

std:hash with access to private members of a class

我想散列一个有两个私有成员的 class,例如:

foo.h

class Foo {
    private:
        std::string a;
        std::string b;

    public:
        Foo (std::string a, std::string b);
        bool operator==(const Foo& other) const;
        bool operator!=(const Foo& other) const;
        std::size_t operator()(const Foo& ) const;
};

namespace std {
    template <> struct hash<Foo> {
        std::size_t operator()(const Foo& cp) const;
    };
}

foo.cpp

Foo::Foo (std::string _a, std::string _b) {
    this->a = _a;
    this->b = _b;
}

bool Foo::operator== (const Foo& other) const {
    return this->a == other.a && this->b == other.b;
}

bool Foo::operator!= (const Foo& other) const {
    return !operator==(other);
}

std::size_t std::hash<Foo>::operator()(Foo const& foo) const {
    std::string f = foo.a; // << This wont compile!
    return 1;
}

在 C++ 中,当最终哈希函数无法访问 foo 的私有成员时,通常如何对 Foo 进行哈希处理。

请随意在您的答案中加入助力或绳降。

您可以将 std::hash<Foo> 声明为 Foofriend:

class Foo {
 private:
  std::string a;
  std::string b;

 public:
  Foo(std::string a, std::string b);
  bool operator==(const Foo& other) const;
  bool operator!=(const Foo& other) const;
  std::size_t operator()(const Foo&) const;

  friend std::hash<Foo>;
};