C++ 使用类模板的static成员

使用类模板的static成员

定义下面这个模板类

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;
};

下面的代码来使用它

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

这样就能通过编译链接了

posted @ 2018-10-15 23:04  弱冠  阅读(824)  评论(0编辑  收藏  举报