模板类的C ++ std :: tr1 :: hash [英] C++ std::tr1::hash for a templated class

查看:163
本文介绍了模板类的C ++ std :: tr1 :: hash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 模板< typename T>事情{...}; 

我想在unordered_set中使用它:

 模板< typename T> class Bozo {
typedef unordered_set< Thing< T> > things_type;
things_type的东西;
...
};

现在类Thing拥有除散列函数外所需的所有东西。我想使这个泛型,所以我尝试类似:

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

尝试使用g ++ 4.7进行编译时,它会尖叫


预期初始化器在'<'


关于

  hash< Thing< T> > 

声明的一部分。任何线索都有助于挽救我头上留下的少数头发。 > 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>)
{
return 42;
}
};
}}

另一种方法是为<$ c $创建一个哈希器c> Thing ,并将其指定为 unordered_set 的第二个模板参数。

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

typedef std :: unordered_set< Thing< T>,Thing_hasher< T>> things_type;


I have this templated class:

template <typename T> Thing { ... };

and I would like to use it in an 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. 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

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&); just specialize the entire 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.

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;

这篇关于模板类的C ++ std :: tr1 :: hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆