当前位置 : 主页 > 编程语言 > java >

c++进阶十四(函数模板的使用)

来源:互联网 收集:自由互联 发布时间:2023-03-22
模板函数定义的一般形式如下所示: //这里class type和typename type作用相同//其实,这里最常用的是使用关键字class,而且二者功能完全相同template class type ret-type func-name(parameter list){ // 函

模板函数定义的一般形式如下所示:

//这里class type和typename type作用相同//其实,这里最常用的是使用关键字class,而且二者功能完全相同template <class type> ret-type func-name(parameter list){ // 函数的主体}

在这里,type 是函数所使用的数据类型的占位符名称。这个名称可以在函数定义中使用。

下面是函数模板的实例,返回两个数中的最大值:

实例

#include <iostream>#include <string> using namespace std; template <typename T>inline T const& Max (T const& a, T const& b) { return a < b ? b:a; } int main (){ int i = 39; int j = 20; cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return 0;}

当上面的代码被编译和执行时,它会产生下列结果:

Max(i, j): 39Max(f1, f2): 20.7Max(s1, s2): World

上一篇:c++进阶十五(类模板的使用)
下一篇:没有了
网友评论