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

最新文章

  1. centos7安装apue.3e时出错处理
  2. hdu4549 矩阵快速幂 + 欧拉降幂
  3. 【转载】PostgreSQL分区表(Table Partitioning)应用
  4. [改善Java代码]不要在finally块中处理返回值
  5. 投资学第一章 investments-introduction
  6. dump文件定位程序崩溃代码行
  7. Android简易实战教程--第十一话《获取手机所有应用信息Engine类详解》
  8. 洛谷 P1691 解题报告
  9. JavaScript常用数组操作方法,包含ES6方法
  10. 从excel表中生成批量SQL,将数据录入到数据库中
  11. FTP模式简式:PORT/PASV/EPRT/EPSV
  12. 利用nginx,腾讯云免费证书制作https
  13. Python学习笔记(三)
  14. Fiddler常用命令
  15. MongoDB 常用的几大GUI工具
  16. 4.2Python数据处理篇之Matplotlib系列(二)---plt.scatter()散点图
  17. linux手动安装sbt过程
  18. Repository mirror 解析
  19. 软工网络15团队作业4——Alpha阶段敏捷冲刺1.0
  20. BeanShell用法(摘抄至网络)

热门文章

  1. 剖析虚幻渲染体系(12)- 移动端专题Part 1(UE移动端渲染分析)
  2. ubuntu install redis
  3. Python基础(类和实例)
  4. 大爽Python入门教程 2-1 认识容器
  5. psutil模块详解
  6. 『学了就忘』Linux软件包管理 — 47、Linux源码包的安装和卸载
  7. liunx下安装mysql(8.0.27)
  8. [bzoj3304]带限制的最长公共子序列
  9. 规格模式(Specification Pattern)
  10. bcftools 提取vcf(snp/indel)文件子集