如何在 C++ 类模板中使用静态变量

BVB*_*VBC 5 c++ static templates

这是来自 geeksforgeeks 的示例。我不明白下面的代码。

template<class T> int Test<T>::count = 0;
Run Code Online (Sandbox Code Playgroud)

count 是外部变量吗?为什么不直接让 static int count = 0 呢?下面列出了 geeksforgeeks 中的描述和代码。

类模板和静态变量:类模板的规则与函数模板相同。类模板的每个实例都有其自己的成员静态变量副本。例如,在下面的程序中有两个实例Test和Test。因此存在静态变量 count 的两个副本。

#include <iostream>

using namespace std;

template <class T> class Test
{  
private:
  T val; 
public:
  static int count;
  Test()
  {
    count++;
  }
  // some other stuff in class
};

template<class T>
int Test<T>::count = 0;

int main()
{
  Test<int> a;  // value of count for Test<int> is 1 now
  Test<int> b;  // value of count for Test<int> is 2 now
  Test<double> c;  // value of count for Test<double> is 1 now
  cout << Test<int>::count   << endl;  // prints 2  
  cout << Test<double>::count << endl; //prints 1

  getchar();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*ain 3

每次使用新类型实例化 Test 对象时,都会从可用模板中为您创建一个新类。(因此,在您的情况下,编译器Test<int>Test<double>根据您的需要创建类)。现在,您可以将Test<int>Test<double>视为从同一模板创建的两个单独的类。

因为有两个类,所以在不同的范围内有两个同名静态变量的副本。是在按需创建的类中template<class T> int Test<T>::count = 0;定义 this 的模板。count

如果您将此定义专门用于某种类型,例如:

template<>
int Test<int>::count = 5;
Run Code Online (Sandbox Code Playgroud)

Test<int>::count7在打印时。而Test<double>::count将保持1不变(不变)。