14.1 - Function templates
来源:互联网 发布:从u盘安装linux 编辑:程序博客网 时间:2024/05/15 23:45
The need for function templates
首先举例你想写一个返回两个数中的最大值,你可以写成这样
int max(int nX, int nY){ return (nX > nY) ? nX : nY;}
这个函数对于int型的数据可以很好的工作。可以如果以后要处理double型的数据怎么办呢?简单来说,你可以重载这个函数
double max(double dX, double dY){ return (dX > dY) ? dX : dY;}
这两个函数除了数据类型是完全一样的。虽然简单,但这有悖重复的代码应该越少越好的原则。
What is a function template?
在C++中,function templates是创建相似函数的模板。function template的基本想法是定义一个函数,却不制定其中部分或全部的变量类型。我们使用占位符,template type parameters来定义函数的变量类型。
显然我们不能直接调用function template,因为编译器不知道怎么处理占位符。所以使用的时候要指明真实的变量类型。
Creating function templates in C++
从第一个例子,我们可以发现有3个地方明确的指明了变量类型,参数nX, nY和返回值。创建function template就需要把这些变量类型替换成占位符.
template <typename Type> // this is the template parameter declarationType max(Type tX, Type tY){ return (tX > tY) ? tX : tY;}
现在,我们仔细分析一下template参数声明。首先是关键字template-这个关键字告诉编译器接下来是template参数列表。所有的参数都放在一对尖括号内。创建一个template类型参数,应该使用关键字typename或者class. 这两个关键字其实一样,但是许多人都使用class,但是笔者认为typename关键字更好,因为类型参数并不一定要是class类型。关键字后面就是占位符类型的名字。如果你有多个类型参数,应该用逗号分开
template <typename T1, typename T2>// template function here
Using function templates
function template的使用很简单,就像一般函数一样。
int nValue = max(3, 7); // returns 7double dValue = max(6.34, 18.523); // returns 18.523char chValue = max('a', '6'); // returns 'a'
Template functions也有一些缺点,首先,老的编译器可能不能很好的支持。其次,难以调试。
- 14.1 - Function templates
- C++templates简单基础--Function Templates
- C++ function templates(1)---《C++ Templates》
- C++ 函数模板( Function templates)
- Why Not Specialize Function Templates
- Function Templates 函数模板——初窥
- C++ use Templates(function && class)
- C++ Type function(9)---《C++ Templates》
- Templates
- templates
- Templates
- Templates
- Templates
- templates
- templates
- templates
- 用 member function templates 接受 "all compatible types"
- 《C++ Template. The Complete Guide》笔记之二 Function Templates
- 同步通信和异步通信以及传输率
- C语言-获得进程或线程ID函数
- java线程学习心得二之线程的两种创建方式以及优异
- Ajax(4):post请求之表单中含有中文时如何处理
- 最近要把php捡一下
- 14.1 - Function templates
- 什么是java序列化,如何实现java序列化?
- servlet工作原理解析
- Android 图片平铺实现方式
- 某大型银行深化系统之三:标准规范
- NMOS和PMOS区别
- 【创业笔记】团队建设--团队氛围的营造
- Android:Layout_weight的深刻理解
- Please ensure that adb is correctly located at 'C:\Users\Administrator\android-sdks\platform-tools\