我在我的頭文件中定義的模板如下:C++:初始化頭文件中聲明的模板構造函數/例程?
template<typename T> class BoundedBuffer {
unsigned int size;
T entries[];
public:
BoundedBuffer(const unsigned int size = 10);
void insert(T elem);
T remove();
};
然而,當我嘗試初始化構造函數:
BoundedBuffer<T>::BoundedBuffer(const unsigned int size = 10) size(size) {
// create array of entries
entries = new T[size];
// initialize all entries to null
for(int i = 0; i < size; i++)
entries[i] = null;
}
我得到以下錯誤(先前的第一線代碼塊爲17):
q1buffer.cc:17: error: âTâ was not declared in this scope
q1buffer.cc:17: error: template argument 1 is invalid
q1buffer.cc:17: error: expected initializer before âsizeâ
謝謝:)它的工作原理。所以我應該將構造函數的實現移動到h文件中? 此外,使用BoundedBuffer作爲我的函數中的參數時,有什麼不對: /*生產者*/ 監製::監製(BoundedBuffer 和緩衝,const int的農產品,const int的延遲) \t緩衝液(緩衝)產生(產生),結果產生(1),延遲(延遲){} 「q1buffer.cc:42:錯誤:在緩衝區之前的預期初始化程序 –
Garrett
是所有必須由幾個c文件使用的模板的實現應移動到標題文件。如果它只侷限於一個C文件,那麼當然你可以將所有內容保存在C文件中。 –
關於你在這個評論中的第二個問題,我不明白! –