[英]c++ overriding default function in templated class
作为学习练习,我想创建自己的哈希表类(是的,我知道std :: unordered_map和std :: unordered set)。 因此,我编写了以下代码:
using std::cout;
using std::endl;
using std::vector;
using std::unique_ptr;
template <class K, class V, class U=std::hash<K>>
class hashTable
{
int order=0;
vector<myNode<K, V>> nodes;
public:
hashTable(U u = U()){}; // : hashPtr(u)
size_t gethash(K key, int level=0, const U & u=U());
};
template<class K, class V, class U>
size_t hashTable<K, V, U>::gethash(K key, int level, const U & u)
{
return u(key) % divisors[level];
}
而且它可以很好地编译,并且在我主要拥有的时候可以达到我的期望:
hashTable<int,int> hast;
for(int i=0;i<40;++i)
cout << "hash of "<<i<<" is " << hast.gethash(i, 2) << endl;
但是,当我编写以下函数时:
size_t nodeHash(myNode<int,int> node) {
int i = node.getkey();
int j = node.getvalue();
std::hash<int> hash_fn;
return hash_fn(i)+hash_fn(j);
}
我主要写:
hashTable < myNode<int, int>, int, nodeHash> hashMyNode;
我收到编译错误:函数“ nodeHash”不是类型名称。
我知道我不知道自己在做什么,因为这些模板化函数对我来说是新的。 我似乎足够了解“危险”。 但是,如果有人能够在正确的方向上微调我或为我提供完整的解决方案,以将外部函数包括到类中(例如std :: unordered_map或std :: sort确实如此),那么我当然会很高兴。
编辑:
auto node = myNode<int, int>(1, 3);
hashTable < myNode<int, int>, int, size_t (*)(myNode<int,int> node)> hashMyNode;
hashMyNode.gethash(node, 2, nodeHash);
我收到以下错误:
Severity Code Description Project File Line Suppression State
Error (active) E1776 function "myNode<K, V>::myNode(const myNode<int, int> &) [with K=int, V=int]" (declared implicitly) cannot be referenced -- it is a deleted function somePrime E:\source\repos\somePrime\somePrime.cpp 139
和
Severity Code Description Project File Line Suppression State
Error C2280 'myNode<int,int>::myNode(const myNode<int,int> &)': attempting to reference a deleted function somePrime e:\source\repos\someprime\someprime.cpp 139
这是指节点变量。
您可以打开std
名称空间,并将hash
模板的节点类型专门化为:
namespace std {
template<>
struct hash<myNode<int, int>>
{
std::size_t operator()(myNode<int, int> const& node) const {
int i = node.getkey();
int j = node.getvalue();
std::hash<int> hash_fn;
return hash_fn(i)+hash_fn(j);
}
};
}
然后创建一个表为:
hashTable < myNode<int, int>, int> hashMyNode;
现在,您可以使用std::hash<myNode<int,int>> hash_fn{}
为节点创建哈希,而不必使用函数作为哈希,但您不必显式创建它们,因为您已经提供了它作为hashTable
默认参数(第三个参数) hashTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.