C++笔记---函数模板

函数模板:

#include<iostream>

using namespace std;

template <typename T>
T max1(T a,T b)
{
    
    
    return a>b?a:b;
}

int main(){
    
    

    float a=10;
    float b=10.01;

    cout<<(max1(a,b))<<endl;
    //调用时max<int>(a,b)也可;
}

一般形式:

template<typename ...>
<返回类型><函数名>(参数表)
{
    
    
    body.......
}

作用:
将多个函数进行整合,可以简化代码。
注意:
typename可以用class代替,即函数模板的类型参数可以为一般数据类型,也可以是类,或者混合。

猜你喜欢

转载自blog.csdn.net/timelessx_x/article/details/114375424