函数模板初探1,由来:有时候,函数的逻辑是一样的,只是参数的类型不同,比如下面int Max(int a,int b){ return a > b ? a : b; } double Max(double a,double b){ return a > b ? a : b; } 2,解决办法,如果参数的类型也可以作为函数的参数,就可以解决了T Max(T a,T b){ return a > b ? a : b; } 3,函数模板写法:template4,函数模板的效率不高,编译器在编译的时候,会根据调用测提供的参数去推导出T1等的类型,并给我们生成对应类型的方法。5,下面的例子,调用的时候,可以明确给定参数的类型,Max(1,2.1),这样一来,即使1和2.1的类型不同,编译也可以通过,如果只用Max(1,2.1),编译就不会通过,当然如果 Max(T1 a,T2 b),也可以解决问题。6,typeid(T).name() 返回T的类型的名字#include #include using namespace std; class Test{ friend ostream& operator<<(ostream &os,const Test &t); public: Test(int d = 0) : data(d){} bool operator>(const Test &t){ return data > t.data ? true : false; } ~Test(){} private: int data; }; ostream& operator<<(ostream &os,const Test &t){ os << "Test::data : " << t.data; return os; } template T Max(T a,T b){ cout << typeid(T).name() << endl; return a > b ? a : b; } int main(){ cout << Max(1,2) << endl; cout << Max('A','B') << endl; cout << Max(1.2f,3.4f) << endl; cout << Max(1.2,3.4) << endl; Test t(10); Test t1(11); cout << Max(t,t1) << endl; //编译不过,因为1和2.1的类型不同,但是模板函数的两个参数的类型是相同的,所以编译器不知道用哪种类型作为函数的参数了。 //cout << Max(1,2.1) << endl; cout << Max(1,(int)2.1) << endl; cout << Max((double)1,2.1) << endl; cout << Max(1,2.1) << endl; cout << Max(1,2.1) << endl; cout << Max<>(1,2) << endl; } (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|