【问题标题】:How to use static variable in a C++ class template如何在 C++ 类模板中使用静态变量
【发布时间】:2016-06-06 06:27:36
【问题描述】:

这是一个来自 geeksforgeeks 的示例。下面的代码我看不懂。

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

count 是一个外部变量吗?为什么不让 static int count = 0? geeksforgeeks 中的描述和代码如下。

类模板和静态变量:类模板的规则是 与函数模板相同 类模板的每个实例化都有 它自己的成员静态变量副本。例如,在下面 程序有两个实例Test和Test。所以静态的两个副本 变量计数存在。

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

【问题讨论】:

    标签: c++ templates static


    【解决方案1】:

    Test 类是一个模板类,这意味着编译器每次遇到实例化不同类型的 Test 的代码时都会生成不同的代码。

    Count 不是外部变量;它是一个静态变量。

    有一个静态变量的实例被其容器类的所有实例共享。

    这里的转折是 Test 是一个模板类,所以实际上并不仅仅是一个“类 Test”。有两种:main()函数会导致编译器生成“class Test”和“class Test”。

    如前所述,静态变量由其容器类的所有实例共享。还注意到,有两种生成的类 Test(int 和 double)。因为 count 是一个静态变量,这意味着需要有一个 count per type 的 Test 实例。因此编译器会同时生成:

    int Test<int>::count = 0;
    

    int Test<double>::count = 0;
    

    请记住,模板的目的是您编写一次代码,然后依靠编译器为使用该模板的所有不同数据类型生成代码。

    【讨论】:

      【解决方案2】:

      count 不是外部变量。它在类之外的原因是因为需要分配变量(并且可能实例化)。当静态变量在类定义中时,它只会告诉编译器“会有这种变量”,但由于定义可能包含在许多源文件中,编译器不会进行任何分配。

      当编译器看到外部定义时,它知道为它分配空间并实例化它(如果它是一个对象)。这可能只发生一次,所以它不能在头文件中。

      【讨论】:

        【解决方案3】:

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

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

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

        template<>
        int Test<int>::count = 5;
        

        Test&lt;int&gt;::count 在打印时将是 7。而Test&lt;double&gt;::count 将保持1(不变)。

        【讨论】:

          猜你喜欢
          • 2019-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-11
          • 2016-03-05
          相关资源
          最近更新 更多