定义下面这个模板类code
template <class T> class Foo { public: static std::size_t ctr; static std::size_t count() { return ctr++; } static void set_ctr(std::size_t v) { ctr = v; } T val; };
下面的代码来使用它it
Foo<int> f1, f2; Foo<int>::set_ctr(10000); auto r1 = f1.count(); auto r2 = f2.count(); Foo<int> fi, fi2; // instantiates Foo<int> class size_t ct = Foo<int>::count(); // instantiates Foo<int>::count ct = fi.count(); // ok: uses Foo<int>::count ct = fi2.count(); // ok: uses Foo<int>::count
这会报错,由于必须在类外部出现数据成员的定义。
在类模板含有 static 成员的状况下,成员定义必须指出它是类模板的成员编译
template <class T> size_t Foo<T>::ctr = 0; // define and initialize ctr
这样就能经过编译连接了模板