c++ - 适用于指针和引用的自定义哈希

标签 c++

我想创建一个可重用的 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/

相关文章:

c++ - 在嵌套循环中使用 OpenMP 的性能问题

c++ - 在 Linux 和 Mac 上处理可移动媒体 USB/CD-ROM 挂载/卸载事件

c++ - CPP 读取文件但 EXE 不读取

c++ - 文字字符串有效但字符串不在 file.open()

C++ 如何在模板中推断 Callable 的类型(参数列表和返回值)

c++ - ZeroMQ - 线程数

c++ - 3.5+ 中缺少 estimateRigidTransform

c++ - 使用 TDM-GCC-64、Cmake 和 CodeBlocks 在 Windows 8 中构建 OpenCV 静态库时出错

c++ - 为什么 C++ 中的 accumulate 定义了两个模板

C++:调整二维 vector 的大小