C ++ std :: tr1 :: hash for a template class

I have this template class:

template <typename T> Thing { ... }; 

and I would like to use it in unordered_set:

 template <typename T> class Bozo { typedef unordered_set<Thing<T> > things_type; things_type things; ... }; 

The Thing class now has everything you need except a hash function. I would like to do this generic, so I will try something like:

 namespace std { namespace tr1 { template <typename T> size_t hash<Thing<T> >::operator()(const Thing<T> &t) const { ... } }} 

Attempts to compile this with g ++ 4.7 ask him to scream

expected initializer to '<

about

 hash<Thing<T> > 

part of the declaration. Any clues will help keep a few remaining hair on my head.

+4
source share
1 answer

You cannot provide specialization only for hash::operator()(const T&) ; just specialize all struct hash .

 template<typename T> struct Thing {}; namespace std { namespace tr1 { template<typename T> struct hash<Thing<T>> { size_t operator()( Thing<T> const& ) { return 42; } }; }} 

Another way to do this is to create a hash for Thing and specify this as the second template argument for unordered_set .

 template<typename T> struct Thing_hasher { size_t operator()( Thing<T>& const ) { return 42; } }; typedef std::unordered_set<Thing<T>, Thing_hasher<T>> things_type; 
+6
source

Source: https://habr.com/ru/post/1479827/


All Articles