template这个关键字告诉编译器,随后的类定义将操作一个或更多未指明的
类型
模板语法的小例子,它产生一个带有越界检查的数组
//: C16:Array.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include "../require.h"
#include <iostream>
using namespace std;
template<class T>
class Array {
enum { size = 100 };
T A[size];
public:
T& operator[](int index) {
require(index >= 0 && index < size,
"Index out of range");
return A[index];
}
};
int main() {
Array<int> ia;
Array<float> fa;
for(int i = 0; i < 20; i++) {
ia[i] = i * i;
fa[i] = float(i) * 1.414;
}
for(int j = 0; j < 20; j++)
cout << j << ": " << ia[j]
<< ", " << fa[j] << endl;
getchar();
} ///:~
看上去像一个普通的类
template<class T>
这里T是替代测试,代表一个类型名称
在Array中,其优势的插入和取出都用相同的函数-即重载的operator[]来
实现。
在main()中,我们看到可以非常容易地创建包含不同类型的Array
Array<int> ia;
Array<float> fa;
这时,编译器两次扩展了Array模板 这被称为实例化,创建两个新的生成类,
可以把它们看做Array_int和Array_float 不同的编译器对名称有不同的
修饰方法
输出
0: 0, 0
1: 1, 1.414
2: 4, 2.828
3: 9, 4.242
4: 16, 5.656
5: 25, 7.07
6: 36, 8.484
7: 49, 9.898
8: 64, 11.312
9: 81, 12.726
10: 100, 14.14
11: 121, 15.554
12: 144, 16.968
13: 169, 18.382
14: 196, 19.796
15: 225, 21.21
16: 256, 22.624
17: 289, 24.038
18: 324, 25.452
19: 361, 26.866