Bikush
Bikush

Reputation: 694

How to implement std::hash for a template class

I have a template class 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?

Upvotes: 6

Views: 5261

Answers (2)

Alexander Hugestrand
Alexander Hugestrand

Reputation: 81

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; }
  };
}

Upvotes: 2

Martein Txz
Martein Txz

Reputation: 763

It looks like you're missing a semi-colon at the end of the definition of the Indexer class.

This works:

#include <functional>

template <int N, class TypeId> struct Indexer {};

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

int main() {
   return 0;
}

Upvotes: 6

Related Questions