【问题标题】:hash for derived class派生类的哈希
【发布时间】:2018-11-30 00:10:04
【问题描述】:

我有一种情况,我派生一个类而不更改其任何数据,因此保留其父级的散列函数就可以了。但是,这并不是开箱即用的:

#include <unordered_set>

struct A { size_t value; };
struct B : public A {};

namespace std
{
    template<>
    struct hash<A>
    {
        typedef A argument_type;
        typedef size_t result_type;
        result_type operator()(argument_type const& a) const noexcept { return a.value; }
    };
}

int main()
{
    std::unordered_set<A> a_set; // works fine
    std::unordered_set<B> b_set; // error: hash<B> not found
}

有没有一种简单的方法可以在不显式实现hash&lt;B&gt; 的情况下完成这项工作?

【问题讨论】:

  • 谷歌搜索“std 哈希派生类”会出现很多点击,包括在这个网站上。你看过它们吗?

标签: c++ templates subclassing


【解决方案1】:

这个呢:

template <class T,
    typename std::enable_if<std::is_base_of<A, T>::value, bool>::type = true // just for the hard error
> using hash = std::hash<A>;

std::unordered_set<A> a_set;
std::unordered_set<B, hash<B>> b_set;

或者您可以将std::hash&lt;A&gt; 直接传递给B 设置为:

std::unordered_set<B, hash<A>> b_set;

【讨论】:

  • 我收到error: redefinition of 'hash' as different kind of symbol
猜你喜欢
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多