//第二十三模板 1什么是模板 /* //未使用模板程序 #include <iostream> using namespace std; void swap(int &rx, int &ry) { int temp = rx; rx = ry; ry = temp; } void swap(float &rx, float &ry) { float temp = rx; rx = ry; ry = temp; } void swap(double &rx, double &ry) { double temp = rx; rx = ry; ry = temp; } int main() { int x=2, y=5; cout<<"交换前,x:"<<x<<" y:"<<y<<endl; swap(x,y); cout<<"交换后,x:"<<x<<" y:"<<y<<endl; float a=2.15f,b=3.14f; cout<<"交换前,a:"<<a<<" b:"<<b<<endl; swap(a,b); cout<<"交换后,a:"<<a<<" b:"<<b<<endl; double aa = 2.153456f, d=5.347283f; cout<<"交换前,aa:"<<aa<<" d:"<<d<<endl; swap(aa,d); cout<<"交换后,aa:"<<aa<<" d:"<<d<<endl; return 0; }*/ /* //使用模板程序 #include <iostream> using namespace std; template<class Type> //定义了一个模板类型Type,关键字template用于每个模板类型声明和定义的开头,尖括号中的模板类型跟有关键字template之后,也可以叫做参数,因为我们也可以定义多个模板类型 //template<class Type1, class Type2> //我们并没有为函数模板类型Type提供一个的类型,而是通过在编译时把类型传递给他们,比如说编译根据传递的类型和我们定义的模板模式重载了三次Tswap函数,我们把这个传递的过程叫做类型参数化 void Tswap(Type &rx, Type &ry) { Type temp = rx; ry = rx; rx = temp; } int main() { int x=2, y=5; cout<<"交换前,x:"<<x<<" y:"<<y<<endl; Tswap(x,y); cout<<"交换后,x:"<<x<<" y:"<<y<<endl; float a=2.15f,b=3.14f; cout<<"交换前,a:"<<a<<" b:"<<b<<endl; Tswap(a,b); cout<<"交换后,a:"<<a<<" b:"<<b<<endl; double aa = 2.153456f, d=5.347283f; cout<<"交换前,aa:"<<aa<<" d:"<<d<<endl; Tswap(aa,d); cout<<"交换后,aa:"<<aa<<" d:"<<d<<endl; return 0; } */