c++ - c ++覆盖模板类中的默认函数
问题描述
作为学习练习,我想创建自己的 Hash Table 类(是的,我知道 std::unordered_map 和 std::unordered 集)。所以,我写了这段代码:
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
this 指的是节点变量。
解决方案
您可以打开命名空间并将您的节点类型的模板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
推荐阅读
- javascript - 在执行下一行之前等待循环完成
- websocket - 接收连接和消息请求并发出消息和连接状态更新的 Websocket 史诗
- go - protoc-gen-go:程序未找到或不可执行
- r - 如何查找和求和两列的重复值?
- python - 从字符串中获取时间范围
- excel - 在 MS Access VBA 中选择 Excel 范围抛出 1004 错误
- r - R 代码:如何使用自己的数据集更正 psych 包中的“解析错误(文本 = x,keep.source = FALSE)”输出
- javascript - 采用 XLSX JSON 格式并将其转换为动态 HTML 表格
- javascript - 为什么 JS 数组不包含 peek() 函数?
- android - 在用作位图的 webp 图像中进行更改(谷歌地图)