加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c/c++ 函数模板实例讲解与分析

发布时间:2020-12-15 04:55:46 所属栏目:百科 来源:网络整理
导读:函数模板初探 1,由来:有时候,函数的逻辑是一样的,只是参数的类型不同,比如下面 int Max(int a,int b){ return a > b ? a : b; } double Max(double a,double b){ return a > b ? a : b; } 2,解决办法,如果参数的类型也可以作为函数的参数,就可以解决

函数模板初探

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

4,函数模板的效率不高,编译器在编译的时候,会根据调用测提供的参数去推导出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;

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读