泛型编程(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++学习笔记 -认识函数模版

相关文章:

  • 2021-12-17
  • 2021-09-08
  • 2022-12-23
  • 2021-04-14
  • 2022-02-18
  • 2021-12-02
  • 2022-01-16
  • 2021-11-03
猜你喜欢
  • 2022-02-05
  • 2022-01-05
  • 2021-11-20
  • 2022-12-23
  • 2022-01-09
  • 2021-08-17
  • 2021-06-20
相关资源
相似解决方案