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