簡體   English   中英

C ++覆蓋模板化類中的默認函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM