函数模板可以适用泛型来定义函数,其中泛型可以是(int, double, float)等替换。在函数重载过程中,通过将类型作为参数传递给模板,可使编译器自动产生该类型的函数。
工作原理:比如需要定义一个比大小的max函数,有三种类型的数据(int,double,float),可能就需要编写三个函数,这样既浪费时间,且容易出错。如:
#include <iostream>
using namespace std;
int Max(int a, int b);
double Max(double x, double y);
float Max(float s, float t);
int main()
{
cout << Max(1, 2) << endl;
cout << Max(3.0, 4.0) << endl;
cout << Max(5.23, 5.24) << endl;
return 0;
}
int Max(int a, int b)
{
return a > b ? a : b;
}
double Max(double x, double y)
{
return x > y ? x : y;
}
float Max(float s, float t)
{
return s > t ? s : t;
}
结果如下:

从上面就可以看出一个很简单的比较大小的函数,居然写的这么繁琐,显然增加了工作量,极大降低了工作效率,因此,函数模板的出现十分有效的解决了这个问题。函数模板允许以任意类型的方式定义函数,有两种形式例如:
形式1:
template <typename Anytype> //template是函数模板的关键字
void Swap(Anytype &a,Anytype &b)
{
Anytype temp;
temp=a;
a=b;
b=temp;
}
形式2:
template <class Anytype> //class是函数模板的关键字
void Swap(Anytype &a,Anytype &b)
{
Anytype temp;
temp=a;
a=b;
b=temp;
}
使用函数模板之后的代码如下:
形式1 :
#include <iostream>
using namespace std;
template <typename T>
T Max(T a, T b);
/* double Max(double x, double y);
float Max(float s, float t); */
int main()
{
cout << Max(1, 2) << endl;
cout << Max(3.0, 4.0) << endl;
cout << Max(5.23, 5.24) << endl;
return 0;
}
template <typename T>
T Max(T a, T b)
{
return a > b ? a : b;
}
形式2:
#include <iostream>
using namespace std;
template <class T>
T Max(T a, T b);
int main()
{
cout << Max(1, 2) << endl;
cout << Max(3.0, 4.0) << endl;
cout << Max(5.23, 5.24) << endl;
return 0;
}
template <class T>
T Max(T a, T b)
{
return a > b ? a : b;
}
结果如下:

对比之下,明显精简了很多。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)