Multiple std::hash specialisation

266 Views Asked by At

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

1

There are 1 best solutions below

2
On

Yes. Make it work for all T where T has a base class of Base. Without requires, this is done using SFINAE and enable_if.