Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c++ - How to extend std::tr1::hash for custom types?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Unfortunately it didn't go down to the level of detail I wanted. By looking through the gcc headers at how they have implemented the standard hash functions I got it working. In view of the dearth of examples (at least at time of writing) on the web I thought this would be as good a place as any to post my own example (which I can confirm works 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 */;
       }
   };
}}

(notice there are two namespaces here - that's just my convention for collapsing nested namespaces)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...