需要多个对不同类型使用同一种算法的函数时,可使用模板。然而,并非所有的类型都使用相同的算法。为满足这 种需求,可以像重载常规函数定义那样重载模板定义。

template <typename T>  
void Swap(T &a,T &b);

template <typename T>

void Swap(T *a,T *b,int n) ;

int main(){

int i = 10;
int j = 20;
Swap(i,j);
cout << i << "," << j << endl;
double x = 10.1;
double y = 10.2;
Swap(x,y);
cout << x << "," << y << endl;
int d1[3] = {1,2,3};
int d2[3] = {3,2,1};
Swap(d1,d2,3);
return 0;

}

template <typename T>

void Swap(T &a,T &b){
T temp;
temp = a;
a = b;
b = temp;
}

template <typename T>

void Swap(T a[],T b[],int n) {
T temp;
for(int i=0;i<n;i++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}

}

在后一个模板中,最后一个参数的类型为具体类型(int),而不是泛型。并非所有的模板参数都必须是模板参数类型。