首页 > 解决方案 > 在 C++ 中,是否可以为所有具有散列成员函数的类定义一个专门的 std::hash?

问题描述

以下代码显示了我想要实现的目标,但我不确定在 C++ 中是否可行。

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

class A : public Hashable {
  std::size_t hash() override const {
     ...
     return hash_value;
  }
};

class B : public Hashable {
  std::size_t hash() override const {
     ...
     return hash_value;
  }
};

namespace std {
  template<>
  struct hash<typename T /*where T matches all type that has hash member function*/> {
    std::size_t operator()(const T& t) {
      return t.hash();
    }
  };
}

标签: c++templates

解决方案


推荐阅读