我们知道一个数据有多种类型 当一个参数类型的函数被另一个数据类型使用时 我们得更改其函数参数类型后 才能使用 这样一来,我们似乎可以 剪切 赋值更改其类型就可以啦
但是这样一来显得代码就冗余了 就像这样
#include<iostream>
using namespace std;
void swap(int& rx,int& ry)
{
int temp=rx;
rx=ry;
ry=temp;
}
void swap(float &ra,float &rb)
{
float temp=ra;
ra=rb;
rb=temp;
}
void swap(double &ra,double &rb)
{
double temp=ra;
ra=rb;
rb=temp;
}
int main()
{
int a=0,b=1;
cout<<"交换前:";
cout<<a<<b<<endl;
swap(a,b);
cout<<"交换后:";
cout<<a<<b<<endl;
double c=0.1,d=0.2;
cout<<"交换前:";
cout<<c<<d<<endl;
swap(c,d);
cout<<"交换后:";
cout<<c<<d<<endl;
return 0;
}
该怎么办 ? 我想更懒一点 我都不想赋值粘贴 那么c++的前辈们站出来了 于是出现了模板的概念 只要更改一点 就可以使用一切的数据类型
就是它了
#include<iostream>
using namespace std;
template <class Type>
int Tswap(Type &rx,Type &ry)
{
Type temp=rx;
rx=ry;
ry=temp;
}
int main()
{
int a=2,b=5;
double x=3.14,y=5.12;
cout<<"交换前:";
cout<<a<<" "<<b<<endl;
Tswap(a,b);
cout<<"交换后:"<<endl;
cout<<a<<" "<<b<<endl;
cout<<"交换前:";
cout<<x<<" "<<y<<endl;
Tswap(x,y);
cout<<"交换后:"<<endl;
cout<<x<<" "<<y<<endl;
}
从上面我们可以大致的明白模板的样子
模板类型Type 关键类型字template用于每个模版类型声明和定义的开头 尖括号中的模板类型跟在关键字template之后 也可以叫参数 因为我们可以定义多个模板类型
template<class Type1,class Type2>
每个参数之间必须用逗号隔,并且每个参数都重新使用关键字class,class 表示该参数是一个类型 ,他与表示类的class不一样 ,他的类型名可以任意去取 type的类型随调用的数据类型灵活变化。这就是模版的一个开头。