讓我們有一個抽象模板類 Stack,它將從模板中的第二個類引數繼承實作。
// file Stack.h
template <class T, template<typename> class Implementation>
class Stack : private Implementation<T>
{
public:
Stack() {}
virtual ~Stack() {}
void push(const T& x) { Implementation<T>::push(x); }
void pop() { Implementation<T>::pop(); }
const T& top() { return Implementation<T>::top(); }
bool empty() const { return Implementation<T>::empty(); }
};
然后,我們有一個類將提供實作,然后用于實體化模板。
// file ListStack.h
template <class Elem>
class ListStack
{
private:
size_t _size;
struct ListNode
{
Elem _elem;
ListNode * _next;
};
ListNode * _top;
~ListStack();
friend class Stack<Elem, ListStack>;
public:
ListStack();
bool empty() const;
const Elem& top() const;
void pop();
void push(const Elem & value);
size_t size() const;
};
我將解構式宣告為私有并將 Stack 類設為友元類,因此它只能在實體化 Stack 類時使用。
// file main.cpp
#include "Stack.h"
#include "ListStack.h"
int main()
{
// ListStack<int> list; cannot instaniate
Stack<int, ListStack> s;
}
問題是為什么 ListStack.h 不需要包含 Stack.h 檔案?
uj5u.com熱心網友回復:
為了編譯模板代碼,需要在某個地方呼叫它。在您的情況下,您有兩個頭檔案都定義了模板應該是什么。對模板的呼叫是在包含 Stack 和 ListStack 的檔案中進行的。由于您在 main.cpp 中創建 Stack 變數,因此您可以避免 List 和 ListStack 在頭檔案中彼此不認識。
我懷疑 Stack 類將由編譯器在您的 main.cpp 中定義,但我不確定我是否正確。
至于 ListStack 類實體化錯誤,那是因為你的解構式是私有的。檢查此鏈接以獲取更多詳細資訊。
編輯:您還需要為您的 ListStack 類創建定義。沒有它,什么都行不通。為簡單起見,我假設您到處都有空定義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473705.html
上一篇:自定義模板類的C 向量作為成員
下一篇:模板如何推斷const指標型別?
