看一些C++代码看到T符号就头痛,不知道怎么用。看了下书,记录在这里。
1.模版函数
如果要编写一个函数比较两个数并指出第一个数是小于,等于还是大于第二个数。我们可能会定义下面的函数,如果有几种类型,我们可能会定义几个重载函数。
//比较两个数,如果相同返回0,如果v1大,返回1,如果v2大,返回-1 int compare(const int &v1, const int &v2) { if(v1 < v2) return -1; if(v2 < v1) return 1; return 0; } int compare(const double &v1, const double &v2) { if(v1 < v2) return -1; if(v2 < v1) return 1; return 0; }
这两个函数几乎相同,唯一不同的是形参的类型。
用模版函数来改写就是下面的程序:
template是一个声明模板的关键字,类型参数一般用T这样的标识符来代表一个虚拟的类型(刚开始我还因为T是关键词,T可以是任意的字符换成R,myType都可以),当使用函数模板时,会将类型参数具体化。typename和class关键字作用都是用来表示它们之后的参数是一个类型的参数。只不过class是早期C++版本中所使用的,后来为了不与类产生混淆,所以增加个关键字typename。
template <typename T> int compare(const T &v1, const T &v2) { if(v1 < v2) return -1; if(v2 < v1) return 1; return 0; } int main(int argc, char* argv[]) { //因为我们定义了模版函数,可以轻松的更改a,b变量的类型,int,double。而不需要更改函数 double a = 1.5,b = 2.5; printf("result:%d\n",compare(a,b));//相当于调用double compare(const double &v1,const double &v2) int j=1,i=2; printf("result:%d\n",compare(j,i));//相当于调用int compare(const int &v1,const int &v2) return 0; }
一个类模版例子:
#include <iostream> using namespace std; template <class T> //定义类模版 class Compare { public : Compare(T a,T b) {x=a;y=b;} T max( ) {return (x>y)?x:y;} T min( ) {return (x<y)?x:y;} private : T x,y; }; int main( ) { Compare<int> cmp1(3,7);//比较整数 cout<<cmp1.max( )<< "is the Maximum of two integer numbers."<<endl; cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<float> cmp2(45.78,93.6); //比较浮点数 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'); //比较字符 cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl; cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl; return 0; }