【问题标题】:std:hash with access to private members of a classstd:hash 可以访问类的私有成员
【发布时间】:2021-06-21 17:03:50
【问题描述】:

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

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 进行哈希处理。

请随意在您的答案中加入 boost 或 abseil。

【问题讨论】:

  • 如果 Foo 有一个名为 std::size_t get_hash() const; ... 的公共成员函数会怎样?
  • 您可以使用friend 声明(注意this requires forward-declaring 您的班级和std::hash 专业化)。恕我直言,这比通过添加另一个不必要的成员函数来污染接口要好。

标签: c++ c++11 stdmap stdset stdhash


【解决方案1】:

您可以做的是将std::hash&lt;Foo&gt; 声明为friendFoo

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

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 2020-01-19
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2014-05-30
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多