我试图编译以下内容:
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};