模板化类的C++ std :: tr1 :: hash

Rog*_*rch 5 c++ hash templates unordered

我有这个模板类:

template <typename T> Thing { ... };
Run Code Online (Sandbox Code Playgroud)

我想在unordered_set中使用它:

template <typename T> class Bozo {
  typedef unordered_set<Thing<T> > things_type;
  things_type things;
  ...
};
Run Code Online (Sandbox Code Playgroud)

现在,除了哈希函数之外,类Thing具有所需的一切.我想使这个通用所以我尝试类似的东西:

namespace std { namespace tr1 {
  template <typename T> size_t hash<Thing<T> >::operator()(const Thing<T> &t) const { ... }
}}
Run Code Online (Sandbox Code Playgroud)

尝试用g ++ 4.7编译它会让它尖叫

在'<'之前预期的初始化程序

有关

hash<Thing<T> >
Run Code Online (Sandbox Code Playgroud)

声明的一部分.任何线索都有助于挽救我头上剩下的少量毛发.

Pra*_*ian 7

你不能只提供专业化hash::operator()(const T&); 只是专注于整个struct hash.

template<typename T>
struct Thing {};

namespace std { namespace tr1 {
    template<typename T>
    struct hash<Thing<T>>
    {
        size_t operator()( Thing<T> const& )
        {
            return 42;
        }
    };
}}
Run Code Online (Sandbox Code Playgroud)

另一种方法是为其创建一个哈希Thing,并将其指定为第二个模板参数unordered_set.

template<typename T>
struct Thing_hasher
{
  size_t operator()( Thing<T>& const )
  {
    return 42;
  }
};

typedef std::unordered_set<Thing<T>, Thing_hasher<T>> things_type;
Run Code Online (Sandbox Code Playgroud)