template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。
声明类模板要增加一行: template<class 类型参数名>
如template<class dataType>其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的dataType将会被int,float,char等替代。
class Compare_int
{
private:
int x,y;
public:
Compare(int a,int b)
{
x=a;
y=b;
}
int getMax()
{
return (x>y)? x:y;
}
};
class Compare_float
{
private:
float x,y;
public:
Compare(float a,float b)
{
x=a;
y=b;
}
float getMax()
{
return (x>y)? x:y;
}
};
class Compare_float
{
private:
float x,y;
public:
Compare(float a,float b)
{
x=a;
y=b;
}
float getMax()
{
return (x>y)? x:y;
}
};
用一个类模板减少重复性的工作:
template<class dataType>
class Compare
{
private:
dataType x,y;
public:
Compare(dataType a,dataType b)
{
x=a;
y=b;
}
dataType getMax()
{
return (x>y)? x:y;
}
};
实例化时必须用实际的类型名去替代虚拟的类型,如Compare<int> cmp1(3,7);
完整代码:
#include <iostream>
using namespace std;
template<class dataType>
class Compare
{
private:
dataType x,y;
public:
Compare(dataType a,dataType b)
{
x=a;
y=b;
}
dataType getMax()
{
return (x>y)? x:y;
}
};
int main()
{
Compare<int> cmp1(3,7);
cout<<cmp1.getMax()<<" is the Maximum of two Integer numbers"<<endl;
Compare<float> cmp2(12.3,23.4);
cout<<cmp2.getMax()<<" is the Maximun of two Float numbers"<<endl;
Compare<char> cmp3('a','b');
cout<<cmp3.getMax()<<" is the Maximun of two Char numbers"<<endl;
return 0;
}