将一个类转化为类模板
(1)写出一个类
(2)将类型需要改变的地方进行替换(如上面的Type)
(3)在类的前面加入关键字template以及函数参数表
(4)定义对象的格式 类名+<Type>+ xx(参数)
比如上面的compare<int> C1(3,5);
(5)切记,模板函数如果定义在类体外,需要在前面加上一行template <函数参数表>。并在类模板名后面用尖括号加上<虚拟函数参数>
比如
template<class Type>
Type compare <Type>::max()
{
//.....
}
一个模板中可以具有多个参数,即可以在一个模板中声明多个自定义的类型,如下面这句话:
template<class T1,class T2>
而我们就可以利用这两个参数声明一个具有2种类型的成员。下面我用一个程序说下演示一下这个问题:
[cpp] view plain copy
#include <iostream>
#include <string>
using namespace std;
template<class T1,class T2=string>
class show
{
public:
void show1(T1 &a){cout<<"show1:"<<a<<endl;}
void show2(T2 &a){cout<<"show2:"<<a<<endl;}
};
int main()
{
show<int> a;
int temp1=5;
string temp2="Hello,C++!";
a.show1(temp1);
a.show2(temp2);
return 0;
}