函数模板

函数模板解决通用问题,将类型当作参数设计,使用方法如下

template<typename 类型名> //类型名是代号,代指所有可利用此模板的类型

如下的Min函数

#include<iostream>
#include<typeinfo>
using namespace std;
class ST
{
public:
 ST(int _a=0):a(_a)
 {
  this->a = _a;
 }
 int operator<(const ST &t)const
 {
  return this->a < t.a ? this->a : t.a;
 }
 friend ostream& operator<<(ostream &out,const ST &t);
private:
 int a;
};
ostream& operator<<(ostream &out,const ST &t)
{
 out<<t.a;
 return out;
}
template <typename type>//函数模板1
type Min(type a, type b)
{
 cout<<typeid(a < b ? a : b).name()<<endl;
 return a < b ? a : b;
}
template <typename type1, typename type2>//函数模板2
type1 Min(type1 a, type2 b)
{
 cout<<typeid(a < b ? a : b).name()<<endl;
 return a < b ? a : b;
}
void main()
{
 cout<<Min(15, 12.1f)<<endl;
 cout<<Min<int>(11.1, 12.1)<<endl;//这里的<int>声明会让编译器以为是不完全声明<int, >,进而去使用函数模板2
 cout<<Min<int>(11.1, (int)12.1)<<endl;//然而这样就可使用函数模板1
 cout<<Min<int,int>(16, 12.1)<<endl;//尽管声明的双参数类型相同,但是只要双参数声明会直接去函数模板2,无论实际参数类型相同与否
 cout<<Min('A', 'a')<<endl;
 ST st(7),st1(6);
 cout<<Min(st, st1)<<endl;//若针对自定义类型,则需要自定义类型重载方法
}

(注:使用typename时记得引入头文件<typeinfo>)

模板不支持隐式转换,如在只存在函数模板1的时候

cout<<Min(15,12.2)<<endl;

是无法通过的,只有进行显式传递类型,

cout<<Min<int>(15,12.2)<<endl;

或者强制转换

cout<<Min(15,(int)12.2)<<endl;

或者设计不同的类型参数

即函数模板2

posted @ 2019-01-29 20:38  C_hp  阅读(240)  评论(0)    收藏  举报