gpt4 book ai didi

c++ - 如何创建可以参数化的哈希函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:03:20 26 4
gpt4 key购买 nike

我想创建一个受模板类型 T 和 E 支持的哈希函数。我使用:

  namespace std {
namespace tr1 {
template<class T, class E> struct hash<my_class<T, E> >
{
public:
size_t operator()(const my_class<T, E>& k) const
{
return ((hash<T>()(k.a()))^ (hash<E>()(k.x()) << 1) >> 1);
}
};
}
}

但我收到如下错误:

 In file included from g.cpp:1:
g.h:35: error: ‘hash’ is not a template
g.h:36: error: explicit specialization of non-template ‘hash’
g.h:76: error: ‘hash’ is not a template
g.h:76: error: ‘hash’ is not a template type

有没有办法专门化哈希函数以便它可以使用模板?

如果不是,我将如何构造一个基于泛型 T 和 E 的哈希函数?

编辑:有人在下面回答,但不完全是我的问题。我对能够定义一个本身使用泛型类型的哈希函数很感兴趣。类似于 hash< some_class < T >> 的东西,其中 T 是泛型类型。

最佳答案

hash 在命名空间 std 中,而不在命名空间 std::tr1 中。请参阅 en.cppreference.com 中的片段有关如何专门化它的示例(当然您也可以部分专门化它):

#include <iostream>
#include <functional>
#include <string>

struct S
{
std::string first_name;
std::string last_name;
};

namespace std
{
template<>
struct hash<S>
{
typedef S argument_type;
typedef std::size_t value_type;

value_type operator()(argument_type const& s) const
{
value_type const h1 ( std::hash<std::string>()(s.first_name) );
value_type const h2 ( std::hash<std::string>()(s.last_name) );
return h1 ^ (h2 << 1);
}
};
}

int main()
{
S s;
s.first_name = "Bender";
s.last_name = "Rodriguez";
std::hash<S> hash_fn;

std::cout << "hash(s) = " << hash_fn(s) << "\n";
}

关于c++ - 如何创建可以参数化的哈希函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com