主要探索函数模板和类模板:
函数模板,实际上是建立一个通用函数,其函数类型和形参类型不具体指定,用一个虚拟的类型来代表。这个通用函数就称为函数模板。
定义函数模板的一般形式为:
template < typename T1,typename T2> 或 template <class T>
T T1 T2 代表是不同类型参数
通用函数定义 通用函数定义
应注意它只适用于函数的参数个数相同而类型不同,且函数体相同的情况,如果参数的个数不同,则不能用函数模板
具体示例:
#include <iostream>
using namespace std;
//template<class T>
template<typename T> //模板声明,其中T为类型参数
T max(T a,T b,T c) //定义一个通用函数,用T作虚拟的类型名
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
int main( )
{
int i1=185,i2=-76,i3=567,i;
double d1=56.87,d2=90.23,d3=-3214.78,d;
long g1=67854,g2=-912456,g3=673456,g;
//调用时和普通函数一样,系统自动完成匹配工作
i=max(i1,i2,i3); //调用模板函数,此时T被int取代
d=max(d1,d2,d3); //调用模板函数,此时T被double取代
g=max(g1,g2,g3); //调用模板函数,此时T被long取代
cout<<"i_max="<<i<<endl;
cout<<"f_max="<<d<<endl;
cout<<"g_max="<<g<<endl;
return 0;
}
运行结果:
类模板:
两个或多个类,其功能是相同的,仅仅是数据类型不同,这时可以使用类模板。它可以有一个或多个虚拟的类型参数。
#include <iostream>
using namespace std;
template <class numtype>
//定义类模板
class Compare
{
public :
Compare(numtype a,numtype b)
{x=a;y=b;}
numtype max( )
{return (x>y)?x:y;}
numtype min( )
{return (x<y)?x:y;}
private :
numtype x,y;
};
int main( )
{
Compare<int> cmp1(3,7);//定义对象cmp1,用于两个整数的比较
cout<<cmp1.max( )<<" is the Maximum of two integer numbers."<<endl;
cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl;
Compare<double> cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较
cout<<cmp2.max( )<<" is the Maximum of two float numbers."<<endl;
cout<<cmp2.min( )<<" is the Minimum of two float numbers."<<endl<<endl;
Compare<char> cmp3('a','A'); //定义对象cmp3,用于两个字符的比较
cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl;
cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl;
return 0;
}
运行结果:
区别:
函数模板的实例化是由编译程序在处理函数调用时自动完成的,而类模板的实例化
必 须由程序员在程序中显式地指定。