我想创建一个可重用的 IdHash 和 IdEqualTo 类,它采用 const 实例(引用、原始指针或智能指针),并返回哈希值或比较结果。
template<class Entity, class Id>
struct IdFunc {
typedef typename std::function<const Id& (const Entity&)> type;
};
template<class Entity, class Id>
struct IdHash {
public:
explicit IdHash(const typename IdFunc<Entity, Id>::type& idFunc) : idFunc_(idFunc) {}
std::size_t operator()(const Entity& o) const {
return std::hash<Id>()(idFunc_(o));
}
private:
typename IdFunc<Entity, Id>::type idFunc_;
};
// IdEqualTo follows the same pattern
我的第一次尝试使用 unordered_set<MyClass, IdHash<string, MyClass>, IdEqualTo<...>>
.由于 MyClass 将是继承层次结构而不是单一类型,因此我需要切换到指针:unordered_set<unique_ptr<MyClass>, IdHash<string, MyClass>, ...>
.现在我需要一个采用 unique_ptr& 的运算符版本。我提供了以下内容
std::size_t operator()(const Entity* o) const {
return std::hash<Id>()(idFunc_(*o));
}
希望unique_ptr<MyClass>&
可以以某种方式转换为 MyClass*
.它没有用。由于此实用程序应该超越存储类型,我如何才能使其与引用、原始指针或智能指针一起使用?
参见 code sample .
谢谢。
最佳答案
没有从智能指针到原始指针的自动转换(尽管您可以使用 get()
)。
为智能指针专门化您的模板,这是在标准库和 boost 中完成的方式。
template <class Inner, class Id>
struct IdHash<std::unique_ptr<Inner>, Id> {
typedef std::unique_ptr<Inner> PtrType;
std::size_t operator() (const PtrType &pointer) const {
return std::hash<Id>()(idFunc_(pointer.get());
}
};
您可能还想创建 std::hash<Id>
只实例一次而不是每次调用 operator()
.
关于c++ - 适用于指针和引用的自定义哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999303/