2011-10-21 53 views
0

我在我的頭文件中定義的模板如下: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â 

回答

4

正確的語法是:

template <typename T> 
BoundedBuffer<T>::BoundedBuffer(const unsigned int size) : 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; 
} 

注意可選參數不應該在函數的定義,但在ONY函數的聲明中聲明。

class aaa 
{ 
    // declaration 
    void xxx(int w = 10); 
}; 

// definition 
void aaa::xxx(int w) 
{ 
    ... 
} 

請注意,模板類的所有內容都應保留在H文件中。 「

」它們必須位於相同的翻譯單元中,在某些庫中將模板實現分離爲一個.tpp(或其他擴展名)文件是相當普遍的,該文件隨後包含在聲明模板的.h中「。正如Michael Price所說。

模板不是正常類型,它們不能鏈接。 它們僅在請求時才被實例化。

請注意,構造函數字段初始值設定項需要「:」字符。

class MyClass 
{ 
public: 
    int x; 

    MyClass() : x(10) { /* note that i used : character */ } 
}; 
+0

謝謝:)它的工作原理。所以我應該將構造函數的實現移動到h文件中? 此外,使用BoundedBuffer 作爲我的函數中的參數時,有什麼不對: /*生產者*/ 監製::監製(BoundedBuffer 和緩衝,const int的農產品,const int的延遲) \t緩衝液(緩衝)產生(產生),結果產生(1),延遲(延遲){} 「q1buffer.cc:42:錯誤:在緩衝區之前的預期初始化程序 – Garrett

+0

是所有必須由幾個c文件使用的模板的實現應移動到標題文件。如果它只侷限於一個C文件,那麼當然你可以將所有內容保存在C文件中。 –

+0

關於你在這個評論中的第二個問題,我不明白! –

1

您必須在頭中實現模板的所有方法,因爲模板的用戶需要能夠看到這些方法爲給定類型實例化它。

1

你的聲明應該是:

template< typename T > 
BoundedBuffer<T>::BoundedBuffer(const unsigned int size) : size(size) {...} 

注意,它也必須在頭文件,如@Dean波維提及。