1

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
    you mean one specialization that works for all your classes that have a `GetHash` method? The question is not quite clear. If you know how to specialize for one you can also specialize for many, but I suppose you are looking for some shortcut – 463035818_is_not_an_ai Sep 10 '21 at 13:44
  • A little nitpicking here: The classes that derive from `Base` ***override*** the `GetHash` function from the base class, not overload. If they were overloaded, then they would use different arguments. – Some programmer dude Sep 10 '21 at 13:44
  • Yes, I absolutely looking for some shortcut, cause there're a lot of classes. – Pavel Lyubkin Sep 10 '21 at 13:47
  • Since your type is polymorphic, You could have all of your containers store a `std::unique_ptr` as the element type, and then you would just need to specialize `std::hash` for `std::unique_ptr`. – NathanOliver Sep 10 '21 at 13:59

1 Answers1

-1

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.

JDługosz
  • 5,592
  • 3
  • 24
  • 45
  • 5
    Could you show how you would do this? `std::hash` only has a single template parameter so I'm not certain how you would do the specialization. – NathanOliver Sep 10 '21 at 13:54
  • I'm afraid it only leads to an error ```error: default template argument in a class template partial specialization``` – Pavel Lyubkin Sep 10 '21 at 13:57