2016-09-07 33 views
0

我試圖編譯下面的封閉類型的靜態數組:類模板

template<typename T> 
class Foo { 
protected: 
    static Foo<T>* pool[5]; 
public: 
    static Foo* Bar() { 
     pool[1] = new Foo(); 
    } 
}; 

int main() { 
    Foo<int>* b = new Foo<int>(); 
    b->Bar(); 
} 

我得到的錯誤:

undefined reference to `Foo<int>::pool' 

如何我會要定義的池陣列?

+0

每天提問,與模板無關,並在常見問題解答中涵蓋。你的書也應該包括在內。必須定義靜態成員。 –

回答

2

您可以像這樣在類之外定義一個模板化類的靜態成員。

// for generic T 
template<typename T> 
Foo<T>* Foo<T>::pool[5] = {0, 0, 0, 0, 0}; 

// specifically for int 
template<> 
Foo<int>* Foo<int>::pool[5] = {0, 0, 0, 0, 0};