【发布时间】: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<B> 的情况下完成这项工作?
【问题讨论】:
-
谷歌搜索“std 哈希派生类”会出现很多点击,包括在这个网站上。你看过它们吗?
标签: c++ templates subclassing