模板的一个小实例

来源:互联网 发布:阿里云 ssh 断开 编辑:程序博客网 时间:2024/04/28 01:15
//需要多个对不同类型使用同一种算法的函数时,可使用模板。模板的好处是,它使生成多个函数定义简单、更可靠。
#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;
}
0 0
原创粉丝点击