函数模板初探
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,函数模板写法:template<typename T1,typename T2, ...>
4,函数模板的效率不高,编译器在编译的时候,会根据调用测提供的参数去推导出T1等的类型,并给我们生成对应类型的方法。
5,下面的例子,调用的时候,可以明确给定参数的类型,Max<int>(1, 2.1),这样一来,即使1和2.1的类型不同,编译也可以通过,如果只用Max(1, 2.1),编译就不会通过,当然如果 Max(T1 a, T2 b),也可以解决问题。
6,typeid(T).name() 返回T的类型的名字
#include <iostream>
#include <typeinfo>
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<typename T>
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<int>(1, 2.1) << endl;
cout << Max<double>(1, 2.1) << endl;
cout << Max<>(1, 2) << endl;
} 继续阅读与本文标签相同的文章
下一篇 :
淘系技术部,“职”想要你
-
技术人看《长安十二时辰》的正确姿势是?
2026-05-18栏目: 教程
-
使用logrotate切割日志
2026-05-18栏目: 教程
-
网站漏洞检测 apache nginx解析绕过上传漏洞
2026-05-18栏目: 教程
-
渗透测试 网站安全基础点web讲解(第一点)
2026-05-18栏目: 教程
-
【阿里云新品发布·周刊】第26期:硬核!阿里云新品动态一手掌握
2026-05-18栏目: 教程
