c++ template实例

来源:互联网 发布:暴雪 腾讯 知乎 编辑:程序博客网 时间:2024/06/13 23:43
/* * templateTest.cpp * *  Created on: 2017年11月10日 *      Author: XXX */#include <iostream>using namespace std;template <typename T>T max1(const T & a, const T &  b){return a>b?a:b;}template <typename T2>class Max{public:Max(T2 a1, T2 b1):a(a1),b(b1){};T2 getMaxValue(){return a>b?a:b;}private:T2 a;T2 b;};int main(void){cout<< "template fuction !!!"<<endl;int max = max1(20,25);cout<< "max = " << max <<endl;char max_c = max1('z','a');cout<< "max_c = " << max_c <<endl;float max_f = max1(5.1,3.0);cout<< "max_f = " << max_f <<endl;cout<< "template class !!!"<<endl;Max<int> int_max(20,25);int imax = int_max.getMaxValue();cout<< "get int max = " << imax <<endl;Max<char> char_max('a','z');char cmax = char_max.getMaxValue();cout<< "get char max = " << cmax <<endl;Max<float> float_max(5.1,3.0);float fmax = float_max.getMaxValue();cout<< "get float max = " << fmax <<endl;return 0;}
上面的是模板函数,下面的是模板类。
模板起到了把类型参数化,或者是类型定义做成多态性,编译器辛苦,减少程序程序员冗余代码,减少负担。


template fuction !!!
max = 25
max_c = z
max_f = 5.1
template class !!!
get int max = 25
get char max = z
get float max = 5.1


原创粉丝点击