C++ 使用指针和引用的自定义哈希
我想创建一个可重用的IdHash和IdEqualTo类,该类接受常量实例(引用、原始指针或智能指针),并返回哈希值或比较结果C++ 使用指针和引用的自定义哈希,c++,C++,我想创建一个可重用的IdHash和IdEqualTo类,该类接受常量实例(引用、原始指针或智能指针),并返回哈希值或比较结果 template<class Entity, class Id> struct IdFunc { typedef typename std::function<const Id& (const Entity&)> type; }; template<class Entity, class Id> struct
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
模板
结构IdFunc{
typedef typename std::函数类型;
};
模板
结构IdHash{
公众:
显式IdHash(const typename IdFunc::type&IdFunc):IdFunc(IdFunc){}
std::size\u t运算符()(常量实体&o)常量{
返回std::hash()(idFunc_uo));
}
私人:
typename IdFunc::type IdFunc\ux;
};
//IdEqualTo遵循相同的模式
我的第一次尝试使用无序集
。因为MyClass将是继承层次结构而不是单一类型,所以我需要切换到指针:unordered\u set
。现在我需要一个版本的操作符,它接受unique_ptr&。我提供了以下信息
std::size_t operator()(const Entity* o) const {
return std::hash<Id>()(idFunc_(*o));
}
std::size\u t操作符()(常量实体*o)常量{
返回std::hash();
}
希望unique\u ptr&
可以以某种方式转换为MyClass*
。它不起作用。既然这个实用程序应该超越存储类型,我如何使它与引用、原始指针或智能指针一起工作
看
谢谢。没有从智能指针到原始指针的自动转换(尽管您可以使用
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());
}
};
模板
结构IdHash{
typedef std::unique_ptr PtrType;
std::size\u t运算符()(常量PtrType和指针)常量{
返回std::hash();
}
};
您可能还希望只创建一次
std::hash
实例,而不是每次调用operator()
时都创建一次实例。智能指针与原始指针之间没有自动转换(尽管您可以使用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());
}
};
模板
结构IdHash{
typedef std::unique_ptr PtrType;
std::size\u t运算符()(常量PtrType和指针)常量{
返回std::hash();
}
};
您可能还希望只创建一次
std::hash
实例,而不是每次调用operator()
添加重载std::size\t operator()(const std::unique\u ptr&o)const
?@immibis下次是否需要使用其他指针类型,如shared\u ptr或E*如何?添加重载std::size\t operator()(const std::unique_ptr&o)const
?@immibis下次是否需要使用其他指针类型,如shared_ptr或E*如何?