How to extend std :: tr1 :: hash for custom types?

How do I enable the STL implementation for my custom types? In MSVC there is a class std::tr1::hash which I can partially specialize with

 namespace std { namespace tr1 { template <> struct hash<MyType> { ... }; } } 

but is this the recommended way? Also, does this work with a GCC implementation? For boost::hash enough to provide a free function size_t hash_value (const MyType&) , is there something similar for the implementation of TR1?

+22
c ++ tr1
Mar 15 '09 at 15:14
source share
4 answers

Yes, this will also work for GCC. I use it in a larger project and it works without problems. You can also provide your own custom hash class for TR1 containers, but it is stated that std :: tr1 :: hash <> is the default hash class. Specialization for custom types seems like a natural way to extend the standard hash function.

+4
Mar 15 '09 at 15:24
source share

I tried to work out the exact syntax for this with unordered associative containers (also using GCC, as the OP asked) and hit this question.

Unfortunately, he did not go down to the level of detail that I wanted. Looking through the gcc headers about how they implemented the standard hash functions, I started working. Due to the lack of examples (at least at the time of writing) on โ€‹โ€‹the Internet, I thought it would be as good as anyone to post my own example (which I can confirm by working with GCC):

 namespace std { namespace tr1 { template <> struct hash<MyType> : public unary_function<MyType, size_t> { size_t operator()(const MyType& v) const { return /* my hash algorithm */; } }; }} 

(note that there are two namespaces here - this is just my agreement to collapse nested namespaces)

+21
Apr 05 '09 at 14:27
source share

Since you are not adding the std library to the std , but only providing specializations, then this is normal.

If you want to provide a more general hashing approach (e.g. a hash for tuples in general), take a look at Boost Fusion. Here is a simple example that will work for most cases (probably with the exception for tuples of tuples)

+3
Mar 15 '09 at 15:44
source share

The following code snippet shows how to specialize std::tr1::unordered_map to map boost::const_string<char> to void* same way that std::string hashes.

 #include <boost/const_string/const_string.hpp> typedef class boost::const_string<char> csc; namespace std { namespace tr1 { template <> struct hash<csc> { public: size_t operator()(const csc & x) const { return std::_Hash_impl::hash(x.data(), x.size()); } }; } } typedef std::tr1::unordered_map<csc, void*> Map; typedef Map::value_type Dual; ///< Element Type. 
0
May 05 '11 at 14:59
source share



All Articles