- 继承和组合提供了重用对象代码的方法
- 模板提供了重用源代码的方法
模板语法
类模板
#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;
}
Array<int> ia;
Array<float> fa;
类模板非内联函数
template<class T>
class Array {
enum { size = 100 };
T A[size];
public:
T& operator[](int index);
};
template<class T>
T& Array<T>::operator[] (int index)
{
require(index >= 0 && index < size,"Index out of range");
return A[index];
}
- template<…>=编译器不在当时为期分配存储空间,而是一直等到模板告知
无类型模板参数
template<class T,size N> class Stack
{
T data[N];
size_t count;
public:
void push(const &T);
};
Stack<int , 100> myFixedStack;
- 内含数字被置于栈。而不是动态内存;
- N的取值不同,会产生唯一的类类型;
默认模板参数
template<class T,size N=100> class Stack
{
T data[N];
size_t count;
public:
void push(const &T);
};
template<class T=int,size N=100> class Stack
{
T data[N];
size_t count;
public:
void push(const &T);
};
Stack<> myStack;
模板参数
tempalte<class T>
class Array
{......};
template<class T,template<class> class Seq>
class Container
{
Seq<T> seq;
public:
void append(const T &t){Seq.push_back(t);}
T * begin(){...}
T * end() {...}
};
int main()
{
Container<int ,Array> container;
container.append(1);
.....
}
typename
- typename可以代替 templaet中的class
tempalte <typename T> class X {};