tags:

views:

1765

answers:

3

How do I allow the STL implementation to pick up my custom types? On MSVC, there is a class std::tr1::hash, which I can partially specialize by using

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

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

+2  A: 

Yes, this will also work for GCC. I'm using it in a bigger project and it works without problems. You could also provide your own custom hashing class for the TR1 containers, but it is specified that std::tr1::hash<> is the default hashing class. Specializing it for custom types seems like the natural way to extend the standard hashing functionality.

sth
+2  A: 

As you are not adding to std library namespace, but only providing the specialisations, then it is perfectly OK.

If you want to provide more generic hashing approach (for example hash for the tuples in general) then have a look at Boost Fusion. Here is a simple example, which will work for most of the cases (probably with the exception for tuple of tuples)

Anonymous
+4  A: 
Phil Nash