C ++覆盖模板化类中的默认函数

时间:2018-09-03 21:11:15

标签: c++ function templates

作为一项学习练习,我想创建自己的哈希表类(是的,我知道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确实如此),我当然会很感激的。 / p>

编辑:

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 

这是指节点变量。

1 个答案:

答案 0 :(得分:0)

您可以打开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{}的形式为节点创建哈希,而不必显式创建它们,因为您已经提供了它的类型作为默认参数(第3个参数)的hashTable

相关问题