首页 > 解决方案 > 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 指的是节点变量。

标签: c++functiontemplates

解决方案


您可以打开命名空间并将您的节点类型的模板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


推荐阅读