[Question]

How many instances of template static member exist? Guess the result of the following code.

(1) 3 3 3

(2) 1 2 3



#include <stdio.h>

 

template <class T>

class TemplateObject

{

public:

  static int var;

};

template <class T> int TemplateObject<T>::var = 0;

 

int main()

{

  TemplateObject<char>  charObject;

  TemplateObject<short> shortObject;

  TemplateObject<int>   intObject;

 

  charObject.var  = 1;

  shortObject.var = 2;

  intObject.var   = 3;

 

  printf("%d %d %d\n",  charObject.var, shortObject.var, intObject.var);}

}








[Answer]

(2) 1 2 3






[Conclusion]

Template supported by C++ is just a directive such as a preprocessor by C(e.g. #define). Not until  declared template code is used in other module, it is evaluated by the compiler.





[Download]

template_static_test.zip  : Compiled in Microsoft Visual Studio 2005