//需要多个对不同类型使用同一种算法的函数时,可使用模板。模板的好处是,它使生成多个函数定义简单、更可靠。
#include "stdafx.h"
#include<iostream>
using namespace std;
template<class Any>
void Swap(Any &a,Any &b);
int _tmain(int argc, _TCHAR* argv[])
{
int i=10;
int j=20;
cout<<"i,j= "<< i <<" , "<< j <<".\n";
cout<<"Using compiler-generated int swapper:\n";
Swap(i,j);
cout<<"Now i,j="<< i <<", "<< j <<".\n";
double x=10.45;
double y=20.87;
cout<<"x,y= "<< x <<" , "<< y <<".\n";
cout<<"Using compiler-generated int swapper:\n";
Swap(x,y);
cout<<"Now x,y="<< x <<", "<< y <<".\n";
system("pause");
return 0;
}
template<class Any>
void Swap(Any &a,Any &b)
{
Any temp;
temp =a;
a=b;
b=temp;
}
#include "stdafx.h"
#include<iostream>
using namespace std;
template<class Any>
void Swap(Any &a,Any &b);
int _tmain(int argc, _TCHAR* argv[])
{
int i=10;
int j=20;
cout<<"i,j= "<< i <<" , "<< j <<".\n";
cout<<"Using compiler-generated int swapper:\n";
Swap(i,j);
cout<<"Now i,j="<< i <<", "<< j <<".\n";
double x=10.45;
double y=20.87;
cout<<"x,y= "<< x <<" , "<< y <<".\n";
cout<<"Using compiler-generated int swapper:\n";
Swap(x,y);
cout<<"Now x,y="<< x <<", "<< y <<".\n";
system("pause");
return 0;
}
template<class Any>
void Swap(Any &a,Any &b)
{
Any temp;
temp =a;
a=b;
b=temp;
}