类模板中的封闭类型的静态数组

时间:2016-09-07 00:07:15

标签: c++

我试图编译以下内容:

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'

如何定义池数组?

1 个答案:

答案 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};
相关问题