模板template
- 模板是对具有相同特性的函数或类的再抽象,模板是一种参数多态性的工具,可以为逻辑功能相同而类型不同的程序提供一种代码共享的机制。
- 一个模板并非一个实实在在的函数或类,仅仅是一个函数或类的描述,是参数化的函数和类。
类型: 函数模板和类模板
- 抽象:
- 变量→类型
- 对象→类
- 函数→函数模板
- 类→类模板
函数模板
template <class T1, class T2,…>
//==============================================
返回类型 functionName(参数表){
//函数模板定义体
}
// 也可以使用 typename替代class
template <typename T1,typename T2,…>
//==============================================
template <class T>
T max (T a, T b)
{
return a>b ? a : b;
}
int i = max (3, 4);
char ch = max (‘a’, ‘A’);
float f = max (5.0, 1.0);
类模板
template<class T1,class T2,int T3>
类模板的成员函数的定义
方法1:在类模板外定义,语法
template <模板参数列表>
返回值类型 类模板名<模板参数名表>::成员函数名 (参数列表)
{。。。};
// ==================================================
#include<iostream>
#include<string>
using namespace std;
const int Size=5;
template<class T>
class Array{
private:
T a[Size];
public:
Array() { for(int i=0;i<Size;i++) a[i]=0; }
T &operator[](int i);
void Sort();
};
template<class T>
T& Array<T>::operator[](int i) {
if(i<0||i>Size-1){
cout<<"\n数组下标越界!\n";
exit(1);
}
return a[i];
}
template<class T>
void Array<T>::Sort(){
for(int i=0;i<Size-1;i++){
int p=i;
for(int j=i+1;j<Size;j++)
if(a[p]<a[j]) p=j;
T t=a[p]; a[p]=a[i]; a[i]=t;
}
}
特化
template <> 返回类型 类模板名<特化的数据类型>::特化成员函数名(参数表){
…… //函数定义体
}
// ========================================================
template<>
void Array<char *>::Sort(){
for(int i=0;i<Size-1;i++){
int p=i;
for(int j=i+1;j<Size;j++)
if(strcmp(a[p],a[j])<0)
p=j;
char* t=a[p];
a[p]=a[i];
a[i]=t;
}
}