c++ - 在 tr1 中为模板类定义散列

标签 c++

我有网关类。 我需要将此类的对象存储在哈希表中(使用 tr1::unordered_set)。 我在另一个上下文中同时使用了 unorderd_set 和 Gateway 类,它们工作正常,但我不知道如何将网关放入无序集中,因为我无法定义它的 hash在 tr1 的命名空间中运行。

我试过:(以及许多其他变体)

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
    }
}

编译器说 this ( typename Gateway<T>) 是错误的。如果我拿()关闭,它假定 >>hash<typename Gateway<T>>()结束是输出流。

虽然我以前做过这个

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

任何人都可以阐明这个问题吗?

更新

感谢解答,但还是有问题编译器说不完整类型的使用无效struct std::tr1::hash<>

当我们使用没有完整定义的类时,就会发生这种错误,但类在声明之前已经完全定义。我已经在没有模板的情况下以非常相似的方式使用了它,没有问题。

最佳答案

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

语法错误。 typename不需要。

正确的语法是这样的:

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

注意我还设置了参数const Gateway<T> &输入,只是为了避免复制!

另请注意,命名空间 tr1不是嵌套的命名空间。

关于c++ - 在 tr1 中为模板类定义散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4773537/

相关文章:

c++ - 删除第一个括号 "("和最后一个括号 "("之间的字符串中的所有字符,包括这些括号 C++

c++ - C++ 适合我的应用程序吗?

c++ - 隐含的constexpr?

c++ - 在没有数组或 vector C++ 的情况下存储值

c++ - Qt调用外部Python脚本

c++ - 当 Qt 信号/槽连接失败时,如何提醒我?

html - 如何检测 C++ 字符串中的 "​"(unicode 的组合)

c++ - intel Vtune的整数加减事件计数在哪里?

c++ - 模板参数推导失败

C++组件对象模型