刚刚看完函数模板(Function Template),感觉这种方法不错,先总结如下,望各位多多指点
当函数重载时,为每一个函数写定义代码的是一件很繁琐的事,有了函数模板可就轻松多啦!
举个例子(max()函数是求一个数组中的最大数)
You can define a template for the function max() as follows:
template<class T> T max(T x[], int len)
{
T max = x[0];
for(int i = 1; i < len; i++)
if(max < x[i])
max = x[i];
return max;
}
上面的那个class也可以换成typename,T代表着不同的数据类型,每次调用函数时都用原来的类型代替T
下面我们来看一个完整的例子
#include <iostream>
using std::cout;
using std::endl;
// Template for function to compute the maximum element of an array
template<typename T> T max(T x[], int len)
{
T max = x[0];
for(int i = 1; i < len; i++)
if(max < x[i])
max = x[i];
return max;
}
int main(void)
{
int small[] = { 1, 24, 34, 22};
long medium[] = { 23, 245, 123, 1, 234, 2345};
double large[] = { 23.0, 1.4, 2.456, 345.5, 12.0, 21.0};
int lensmall = sizeof small/sizeof small[0];
int lenmedium = sizeof medium/sizeof medium[0];
int lenlarge = sizeof large/sizeof large[0];
cout << endl << max(small, lensmall);
cout << endl << max(medium, lenmedium);
cout << endl << max(large, lenlarge);
cout << endl;
return 0;
}
输出结果如下:
34
2345
345.5
Note that using a template doesn’t reduce the size of your compiled program in any way. The compiler generates a version of the source code for each function that you require. In fact, using templates can generally increase the size of your program, as functions can be created automatically even though an existing version might satisfactorily be used by casting the argument accordingly.