C++学习17:函数模板

来源:互联网 发布:千千自动发卡源码 编辑:程序博客网 时间:2024/05/30 04:44

函数模板是通用的函数描述,通过将类型作为参数传递给模板,可使编译器生成该类型的函数。
当函数形式完全相同,只是参数类型不同时,可以使用函数模型,这样可以极大的减少代码量,便于维护。

函数模板声明形式如下:

template<typename 数据类型参数标识符><返回类型><函数名>(参数表){    函数体}

其中template和typename是固定的标识符,不可更好。为了使用简单,数据类型参数标识符常会使用T。

例1:

#include<iostream>using namespace std;template<typename T>void Swap(T &a,T &b){    T c;    c=a;    a=b;    b=c;} int main(){    int a=5;    int b=3;    Swap(a,b);    cout<<"a:"<<a<<" "<<"b:"<<b<<endl;    double c=1.2;    double d=3.6;    Swap(c,d);    cout<<"c:"<<c<<" "<<"d:"<<d<<endl;    system("pause");}

结果如下:

a:3 b:5c:3.6 d:1.2请按任意键继续. . .

例2:

#include<iostream>using namespace std;template<typename T1,typename T2>T2 Add(T1 a,T2 b){    T2 c;    c = a+b;    return c;} int main(){    int a=5;    double b=1.2;    cout<<Add(a,b)<<endl;    double c=1.2;    int d = 5;    cout<<Add(c,d)<<endl;    system("pause");}

结果如下:

6.26请按任意键继续. . .

可以看到,通过函数模板,函数会自动根据输入参数的类型进行转换,这样可以极大减少代码量。