C++ 重写<T> T 派生类的哈希
C++ Overriding hash<T> for derived classes of T
几个问题:
- 下面的代码没有编译(请参阅下面的注释)
- 如果我想让Bar和Baz返回id()作为它们的哈希值,我是否也必须重写它们的哈希函数
#include <functional>
class Foo
{
public:
Foo(short id);
short id() const;
private:
const short id_;
};
class Bar : public Foo {};
class Baz : public Foo {};
Foo::Foo(short id) :
id_(id)
{}
short Foo::id() const
{
return id_;
}
namespace std
{
template <> struct hash<Foo> //hash is not a class template
{ //explicit specialization of non-template std::hash
size_t operator()(const Foo& foo) const
{
return hash<short>()(foo.id()); //std::hash is not a template
}
};
}
问题是const
引用正在传递给hash::operator()
,但Foo::id()
未声明为const
。这将阻止您在Foo
的任何const
实例上调用id()
。要解决此问题,只需像一样声明函数const
class Foo
{
public:
short id() const;
};
如果定义std::hash
的实例并传递其中一个派生类作为模板参数,则需要为每个派生类提供专门化。如果您只是将派生类的实例传递给std::hash<Foo>
,则不需要为它们提供专门化。
此外,请确保您使用的是C++11编译器(必要时启用C++11模式),并在注释中包含Kerrek提到的<functional>
标头。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 使用Qt C++计算类似Git的SHA1哈希
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 用C++将哈希表写入文件并从文件中恢复
- c++找不到具有相同哈希的无序集合元素
- 哈希文件递归并保存到矢量Cryptopp中
- 对 pair<pair<int,int>pair<int,int unordered_map进行哈希处理>>
- 直接在 unordered_map 的方法中使用哈希,而不是生成哈希的用户定义对象
- 如何为字符串生成唯一但一致的 N 位哈希(小于 64 位)?
- 使用对象的基类部分模板专用化对对象进行哈希处理::哈希
- boost::包含提升单元的元组的哈希值
- 使用 Key 对 C++ 中的哈希映射进行排序. 无法排序
- C++中的并发哈希表
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 在具有开放寻址的哈希表中插入节点 [优化逻辑]
- 与C++哈希表的基础知识混淆
- 如何为位集找到/实现一个好的哈希函数
- C++ 重写<T> T 派生类的哈希
- 使用哈希表中的派生类搜索函数