zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    20145307陈俊达《网络对抗》Exp6 信息搜集与漏洞扫描
    20145307陈俊达《网络对抗》Exp5 MSF基础应用
    微服务负载均衡 —— ribbon
    微服务注册与发现 —— eureka
    shiro
    unix网络编程——I/O多路复用之epoll
    unix网络编程——TCP套接字编程
    java异常处理及自定义异常的使用
    磁盘调度算法寻道问题
    关于mybatis的思考(3)——ResultMaps的使用
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3444425.html
Copyright © 2011-2022 走看看