1. 程式人生 > >C++ 使用類模板的static成員

C++ 使用類模板的static成員

++ 成員 定義 ant temp count() public r+ clas

使用類模板的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

這樣就能通過編譯鏈接了

C++ 使用類模板的static成員