类模板-template
2014-09-21 09:40
127 查看
template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。
声明类模板要增加一行: template<class 类型参数名>
如template<class dataType>其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的dataType将会被int,float,char等替代。
实例化时必须用实际的类型名去替代虚拟的类型,如Compare<int> cmp1(3,7);
完整代码:
声明类模板要增加一行: template<class 类型参数名>
如template<class dataType>其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的dataType将会被int,float,char等替代。
class Compare_int { private: int x,y; public: Compare(int a,int b) { x=a; y=b; } int getMax() { return (x>y)? x:y; } }; class Compare_float { private: float x,y; public: Compare(float a,float b) { x=a; y=b; } float getMax() { return (x>y)? x:y; } }; class Compare_float { private: float x,y; public: Compare(float a,float b) { x=a; y=b; } float getMax() { return (x>y)? x:y; } }; 用一个类模板减少重复性的工作: template<class dataType> class Compare { private: dataType x,y; public: Compare(dataType a,dataType b) { x=a; y=b; } dataType getMax() { return (x>y)? x:y; } };
实例化时必须用实际的类型名去替代虚拟的类型,如Compare<int> cmp1(3,7);
完整代码:
#include <iostream> using namespace std; template<class dataType> class Compare { private: dataType x,y; public: Compare(dataType a,dataType b) { x=a; y=b; } dataType getMax() { return (x>y)? x:y; } }; int main() { Compare<int> cmp1(3,7); cout<<cmp1.getMax()<<" is the Maximum of two Integer numbers"<<endl; Compare<float> cmp2(12.3,23.4); cout<<cmp2.getMax()<<" is the Maximun of two Float numbers"<<endl; Compare<char> cmp3('a','b'); cout<<cmp3.getMax()<<" is the Maximun of two Char numbers"<<endl; return 0; }
相关文章推荐
- C++设计模式十--TemplatePattern(模板方法模式)
- C++ Template 基础篇(二):类模板
- JS模板引擎---腾讯artTemplate的使用
- VTemplate模板引擎的使用--高级篇
- 使用PowerShell找出具体某个站点所使用的模板(Web Template)名称?
- 有关C++模板(template)的编译错误“error LNK2019: 无法解析的外部符号”的分析
- 扩展Repeater——让Repeater具有EmptyDataTemplate模板功能!
- How to read the environment variables in groovy email template 邮件模板中读取系统环境变量
- 设计模式之模板方法模式Template
- C++ Template学习笔记之函数模板(6)——模板显式特化
- 微信小程序模板(template)使用详解
- UE4 C++类模板 template <class T>
- JavaScript Template JST模板引擎—Trimpath ( 转 )
- VTemplate模板引擎的使用--入门篇
- html5前端开发的干货模板“text/tpl” script template
- Page Template(页模板)
- Xamarin XAML语言教程构建ControlTemplate控件模板 (三)
- c++ template(6)模板术语
- Xamarin XAML语言教程构建ControlTemplate控件模板 (四)
- C++ - 非类型模板参数(nontype template parameters) 使用 及 代码