1

Following code shows what I want to achieve, but I'm not sure whether it is possible in 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();
    }
  };
}
jonspaceharper
  • 4,207
  • 2
  • 22
  • 42
PeopleMoutainPeopleSea
  • 1,492
  • 1
  • 15
  • 24
  • The short answer is: no, not cleanly. Would it work for you to define an abstract class that defines this `hash()`, have all these classes inherit from it, and explicitly specify `CallHashFromThisAbstractClass` helper class as the hash function, wherever it's called? – Sam Varshavchik Nov 14 '19 at 01:49
  • C++ doesn't really give you the reflection tools to even answer the "all classes that have `hash` as a function" question. This is something you need to implement deliberately, not automatically. You can make a template function that can work on any class that has `hash` defined, and will error out during compile if used on one that doesn't. – tadman Nov 14 '19 at 01:50
  • One thing to consider: Could you achieve your desired effect with a C++ lambda? – tadman Nov 14 '19 at 01:53
  • 2
    `std::enable_if_t` or would be called for, but you can’t partially specialize in `std` that way, if I understand correctly. – jonspaceharper Nov 14 '19 at 02:18
  • Possible duplicate of [Is it possible to write a template to check for a function's existence?](https://stackoverflow.com/questions/257288/) – Remy Lebeau Nov 14 '19 at 17:01
  • Remy Lebeau I know how to check a function's existence. Thank you Sam Varshavchik, your clear answer is what I wanted. – PeopleMoutainPeopleSea Nov 15 '19 at 01:36

0 Answers0