C++学习笔记 -认识函数模版

泛型编程(Generic Programming,简称GP)就是实现一个通用的标准容器库,提高程序的效率和通用性。

泛型编程的基础是模版,模版可以分为函数模版类模版。​

函数模板实例:

#include

using namespace std;

template

T const &max(T const &a,T const & b)

{

return a>b?a:b;

}

void main()

{

cout<<"max(10,9)="<<max(10,9)<<endl;

cout<<"max(5.6,7.8)="<<max(5.6,7.8)<<endl;

cout<<"max('A','C')="<<max('A','B')<<endl;

//如果比较的是两个不同类型不能编译通过,错误有三种解决

//1.对实参强制转换

cout<<"max(7.8,8)="<<max(static_cast (7),8.6)<<endl;

//2.显示指定或者限定虚拟参数T的类型

cout<<"max(7.8,8)="<<max(7,8.6)<<endl;

//3.指定两个参数可以具有不同的类型。

//template

}

C++学习笔记 -认识函数模版