Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement std::hash for a class template

I have a class template looking like this:

template <int N, class TypeId> class Indexer {
...
}

and I want to use it in std::unordered_map, I need a hash function. In the codebase we already had something similar (but on an untemplated class) so I tried to do it like this:

namespace std {
template <int N, class TypeId>
struct hash<Indexer<N, TypeId> > {
    size_t operator()(const Indexer<N, TypeId>& id) const noexcept {
        ...
    }
};
}

It is also quite similar to another answer. Unfortunately this does not work, just gives a bunch of unhelpfull errors. Any insights?

like image 612
Bikush Avatar asked Aug 13 '26 00:08

Bikush


1 Answers

Using Visual Studio 2022, with C++ 14, I also got errors, and neither solution above worked. Omitting the template arguments after "hash" did the trick for me.

namespace std {
  template <int N, class TypeId>
  struct hash {
    size_t operator()(const Indexer<N, TypeId>& id) const noexcept { return 0; }
  };
}
like image 95
Alexander Hugestrand Avatar answered Aug 14 '26 13:08

Alexander Hugestrand