I have a class
class Base {
...
virtual size_t GetHash() = 0;
...
};
and a number of classes, inherited from Base, that override GetHash().
I want to use these classes as a key in unordered_map or unordered_set. Currently I achieve it by using
struct HashKey
{
template <typename T>
size_t operator()(const T & obj) const
{
return obj.GetHash();
}
};
as a Hash class in unordered_map template (like unordered_map<MyDerived, int, Hashkey>).
According to this question, I can explicitly specialize std::hash<T> for my own class and totally works fine, but I'm interested if there any way to specialize it for multiple classes?
I'm using C++17
Yes. Make it work for all T where T has a base class of
Base. Withoutrequires, this is done using SFINAE andenable_if.