小编Fle*_*cto的帖子

将 std::hash 专门化为派生类

我有一个抽象基Hashable类,可以对其进行散列派生。我现在想扩展std::hash到所有从Hashable.

下面的代码应该完全做到这一点。

#include <functional>
#include <type_traits>
#include <iostream>

class Hashable {
public:
    virtual ~Hashable() {}
    virtual std::size_t Hash() const =0;
};

class Derived : public Hashable {
public:
    std::size_t Hash() const {
        return 0;
    }
};

// Specialization of std::hash to operate on Hashable or any class derived from
// Hashable.
namespace std {
template<class C>
struct hash {
  typename std::enable_if<std::is_base_of<Hashable, C>::value, std::size_t>::type
  operator()(const C& object) const {
    return object.Hash();
  }
};
}

int …
Run Code Online (Sandbox Code Playgroud)

hash gcc template-specialization c++11 stdhash

7
推荐指数
1
解决办法
2079
查看次数

标签 统计

c++11 ×1

gcc ×1

hash ×1

stdhash ×1

template-specialization ×1