[英]C++ std::tr1::hash for a templated class
I have this templated class: 我有这个模板类:
template <typename T> Thing { ... };
and I would like to use it in an unordered_set: 我想在unordered_set中使用它:
template <typename T> class Bozo {
typedef unordered_set<Thing<T> > things_type;
things_type things;
...
};
Now class Thing has everything it needs except a hash function. 现在,除了哈希函数之外,类Thing具有所需的一切。 I would like to make this generic so I try something like:
我想使这个通用所以我尝试类似的东西:
namespace std { namespace tr1 {
template <typename T> size_t hash<Thing<T> >::operator()(const Thing<T> &t) const { ... }
}}
Attempts to compile this with g++ 4.7 have it screaming 尝试用g ++ 4.7编译它会让它尖叫
expected initializer before '<'
在'<'之前预期的初始化程序
about the 有关
hash<Thing<T> >
part of the declaration. 声明的一部分。 Any clues will help save the few remaining hairs on my head.
任何线索都有助于挽救我头上剩下的少量毛发。
You cannot provide a specialization for just hash::operator()(const T&)
; 你不能只为
hash::operator()(const T&)
提供专门化; just specialize the entire struct hash
. 只是专门化整个
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;
}
};
}}
Another way to do this is to create a hasher for Thing
, and specify this as the second template argument for the unordered_set
. 另一种方法是为
Thing
创建一个hasher,并将其指定为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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.