意义:将一个数据类型做为参数进行传递,这样不需要为每个数据类型都写相同的代码。
C++中使用两个关键字来支持模板:‘template’'和‘typename’. 第二个关键字也可以使用'class'来替换
函数模板 原型:
template
返回值类型 模板名(形参表)
{
函数体
}
例程1:
#includeusing namespace std; template //类型参数 void Swap(T & x, T & y) { T tmp = x; x = y; y = tmp; } int main() { int n = 5, m = 4; Swap(n, m); //编译器自动生成 void Swap (int &, int &)函数 cout << "n=" << n << " m="< #include using namespace std; template //参数类型 T MaxElement(T a[], int size) //size是数组元素个数 { T tmpMax = a[0]; for (int i = 1; i < size; ++i) if (tmpMax < a[i]) tmpMax = a[i]; return tmpMax; } int main() { int a[5] = { 1,5,2,3,4 }; cout << MaxElement(a, 5) << endl; return 0; }
根据实参 a 的类型,编译器通过 MaxElement 模板自动生成了一个 MaxElement 函数,原型为:int MaxElement(int a[], int size);
类模板原型:
template
class test{
private:
T data_member;
......
}
例程1:
#includeusing namespace std; template class Array { private: T* ptr; int size; public: Array(T arr[], int s); void print(); }; template Array ::Array(T arr[], int s) { //构造函数 ptr = new T[s]; size = s; for (int i = 0; i < size; i++) ptr[i] = arr[i]; } template void Array ::print() { for (int i = 0; i < size; i++) cout << " " << *(ptr + i); cout << endl; } int main() { int arr[5] = { 1,3, 5, 7, 9 }; Array a(arr, 5); a.print(); return 0; }
多个模板参数:
#includeusing namespace std; template class A { public: A(T a,U b ) { cout << "a="< a('a','0'); A b(5,6); return 0; }
继承中的类模板语法
#includeusing namespace std; template //定义类模板 class A { public: A(T x) { t = x; } void out() { cout << t << endl; } protected: T t; }; class B : public A < int>//子类B从模板类A继承 { public: B(int i) : A (i) { } void printB() { cout << "A:" << t << endl; } protected: private: }; void pintBB(B &b) { b.printB(); } void printAA(A &a) { a.out(); } void main() { A a(100); printAA(a); B b(10); b.printB(); return; }



