0

以下のクラス 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;  
  Test<int> b;  
  Test<double> c;  
  cout << Test<int>::count   << endl;  // prints 2  
  cout << Test<double>::count << endl; //prints 1

  getchar();
  return 0;
}

出力: 2 1

Test と Test の 2 つのインスタンスがあると思います (Test と Test の呼び出し中)。しかし、2つの異なるタイプがあるため、intとdoubleの2つのインスタンスがある理由を知りたいですか?? もしそうなら、異なるデータ型と同じデータ型に対してカウント変数がどのように追跡されていますか?? これは簡単な質問かもしれませんが、その背後にある基本的なプロセスを知りたいだけですか?

4

4 に答える 4

0

2 つの異なるクラスがあります。

指定された各クラス テンプレートは、異なるクラス タイプです。とは異なるクラス型のクラス名も
同様です。Test<int>Test<double>

コンパイラは、これらのクラスごとに個別のコードを生成するため、2 つの異なる静的変数が生成されます。

さらに、ヘッダーを含む各コンパイル単位のコードを作成します (コードは必要な場所に「挿入」されるため)。

したがって、2 つの異なる .cpp ファイルの 2 つの異なるクラスでそれを出力すると、同じテンプレート化されたクラス タイプであっても、コンパイル ユニットごとに異なるカウンターがあることがわかります。

于 2013-04-11T13:22:40.520 に答える
0

Yes, you get one instance of:

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

for every type of T. And of course an instantiated

  Test()
  {
    count++;
  }

Imagine that you added:

  Test()
  {
    val = 0;
    count++;
  }

You immediately see why you have to have another function for each type. And Test<int> is a different class than Test<double>.

The full name of each of the count variables are:

Test<int>::count
Test<double>::count

Which the compiler will "mangle" into something along the lines of count_Test$i_i and count_Test$D_i respectively (I just made that up, and it may well be quite different in reality)

于 2013-04-11T13:23:20.923 に答える