[英]Templating a List in C++
我正在編寫一個程序,它需要一個我不久前寫的 SkipList,但現在我需要模板化它,因為它需要使用我創建的自定義 class。 我遇到的問題是在列表 class 中創建節點。我在所有方法上都使用template <class t>
但我認為由於節點和 SkipList class 使用template <class t>
,相同的class t
會干擾彼此什么的。
在我的 SkipList.h 中,我有方法說
Node <t>* createnode<t>(t,int);
在 SkipList.cpp 中,該方法說
template <class t>
Node<t>* SkipList<t>::createnode(t value, int level) {
Node<t> *n = new Node<t>(value, level);
return n;
}
這在 .h 文件中給出了一個錯誤,提示Template specialization requires 'template<>'
,當我添加它時,它替換了代碼
template<> Node<t>* createnode<t>(t,int);
但是然后 my.cpp 文件說不再有 function 定義。
有誰知道我哪里出錯了或者我錯過了什么? 非常感謝您的幫助。 如果有人需要澄清,我的 GitHub 在這里
需要注意的幾點:
.cpp
文件中定義模板。using namespace std;
可以而且將會導致討厭的事情,尤其是當像這樣包含在 header 中時。bits/stdc++.h
。 現在解決代碼中的一些問題。 我不確定template <class t, class t>
是否有效,但充其量在這種情況下它是無用的。 解決您的問題:是的,兩個class t
會相互干擾,但您不需要兩個不同的t
。 您不能創建一個t
與List
類型不匹配的Node<t>
嗎? 現在,即使您遇到需要的情況,您也可以使用template <class T1, class T2>
。
現在固定的實現看起來像這樣:
template <class T>
class SkipList {
int MAX_LEVEL;
float p;
Node<t>* header;
int level;
public:
SkipList<T>(int,float) { /* Include definition here */}
int randomlevel() { /* Include definition here */}
void insert(T) { /* Include definition here */}
void remove(T) { /* Include definition here */}
bool find(T) { /* Include definition here */}
void print() { /* Include definition here */}
Node<T>* createnode(T, int) { /* Include definition here */}
};
同樣, Node
也應該固定(包括構造函數的定義)。
您在帖子中提到的另一件事是模板專業化。 你可以在這里閱讀它。
您的Node
/ SkipList
類之間的某處也有 memory 泄漏。 考慮轉向智能指針。
最后,我強烈建議您 go 在繼續之前學習 C++ 的基礎知識。 在你能走之前你不能跑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.