Templates and Static variables in C++

 

  

  Function templates and static variables:
  Each instantiation of function template has its own copy of local static variables.

  For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist.

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <typename T> void fun(const T& x)
 5 {
 6     static int i = 10;
 7     cout << ++i;
 8     return;
 9 }
10 
11 int main()
12 {    
13     fun<int>(1);  // prints 11
14     cout << endl;
15     fun<int>(2);  // prints 12
16     cout << endl;
17     fun<double>(1.1); // prints 11
18     cout << endl;
19     getchar();
20     return 0;
21 }

  Output of the above program is:

   11
    12
    11

  Class templates and static variables:
  The rule for class templates is same as function templates, Each instantiation of class template has its own copy of member static variables.

  For example, in the following program there are two instances Test and Test. So two copies of static variable count exist.

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 template <class T> class Test
 6 {  
 7 private:
 8     T val; 
 9 public:
10     static int count;
11     Test()
12     {
13         count++;
14     }
15     // some other stuff in class
16 };
17 
18 template<class T> int Test<T>::count = 0;
19 
20 int main()
21 {
22     Test<int> a;  // value of count for Test<int> is 1 now
23     Test<int> b;  // value of count for Test<int> is 2 now
24     Test<double> c;  // value of count for Test<double> is 1 now
25     cout << Test<int>::count   << endl;  // prints 2  
26     cout << Test<double>::count << endl; //prints 1
27     
28     getchar();
29     return 0;
30 }

  Output of the above program is:

    2
    1

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  22:16:57

posted @ 2013-11-26 22:17  虔诚的学习者  阅读(322)  评论(0编辑  收藏  举报