开发者

defining hash in tr1 for a template class

I have the class Gateway. I need to store object of this class in a hash table (using tr1::unordered_set). I've used both the unorderd_set and the class Gateway in another context and they work fine, yet I can't figure how to put a gateway in a unordered set because I can't define its hash function in tr1's namespace.

I've tried: (and many other variants)

namespace std {
    namespace tr1 {
        template<> <typename T> inline size_t hash<(typename Gateway<T>)>::operator()(Gateway<T> gT) const {
            return gT.getCore()->hash();   //!DOESN't WORK
    }
}

The compiler says the this (typename Gateway<T>) is wrong. If i take the () off, it assumes the >> in the end of hash<typename Gateway<T>>() is the output stream.

While in the past i've done this

namespace std {
    namespace tr1 {
        template<> inline size_t hash<Board>::operator()(Board b) const {
            return b.hash();            //!WORKS FINE
        }
    }
}

Can anyone shed some light on the problem?

Update

Thanks for the answer yet there is still a problem The compiler says invalid use of incomplete type struct std::tr1::hash<>

This sort of error happens when we use the class without its complete definition, yet t开发者_StackOverflow中文版he class is fully defined before the declaration. I've already used this without templates in a very similar fashion without a problem.


template <typename T> 
inline size_t hash<(typename Gateway<T>)>::operator()(Gateway<T> gT) const 

Wrong syntax. typename is not required.

Correct syntax is this:

namespace tr1
{
    template <typename T> 
    inline size_t hash<Gateway<T> >::operator()(const Gateway<T> & gT) const 
    {
          return gT.getCore()->hash();          
    }
}

Notice I also made the parameter const Gateway<T> & type, just to avoid copy!

Also notice, the namespace tr1 is not a nested namespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜