c++入门----模板

一.为什么要定义模板

  1. 当我们定义一个加法函数的时候,可能存在以下几种情况,int+int,int+float,flaot+float等等情况,这时候就需要我们定义多个操作相同的加法函数,这样显然是非常繁琐也是没有必要的。
  2. 模板的引入就是为了解决这一问题。该编程方式称为“泛型编程”,它的引入大大简化了程序的代码量,保持了结构的清晰,提高的程序设计的效率。

二. 函数模板的定义

  1. 定义如下:
template<模板参数表>
放回类型 函数名(参数列表)
{
	函数体
}
  1. 关键字template放在模板的定义前面,模板参数表不能为空。class或typename 修饰的类型参数代表一种类型,非类型参数由已知类型符,代表一个常量表达式。
template<class Any,class Another,int number>
double fun(Any a,int b, Another c)
{
}

三.函数模板的使用

  1. 隐式实例化,下面模板的参数类型直到该函数真正被调用的时候才被决定。
#include<iostream>
using namespace std;
template<class Ex>
Ex Greater(Ex x, Ex y);
int main(void)
{
	int intX=1,intY=2;
	double dblx = 3.0, dbly = 2.5;
	cout<<Greater(intX,intY)<<endl;
	cout<<Greater(dblx,dbly)<<endl;
	return 0;
}
template<class Ex>
Ex Greater(Ex x, Ex y)
{
	return x>y?x:y;
}
  1. 显式实例化,每个模板函数只能被显式实例化一次,否则会出现重定义。
#include<iostream>
using namespace std;
template<class Ex>
Ex Greater(Ex x, Ex y);
template int Greater<int> (int ,int );  #显式实例化函数模板
int main(void)
{
	int intX=1,intY=2;
	double dblx = 3.0, dbly = 2.5;
	cout<<Greater(intX,intY)<<endl;
	cout<<Greater(dblx,dbly)<<endl;
	return 0;
}
template<class Ex>
Ex Greater(Ex x, Ex y)
{
	return x>y?x:y;
}
  1. 特化,c++引入了特化来解决某些类型在函数中的特殊操作,当编译器寻找到与函数调用的特化时,先使用特化的定义,不在使用模板函数,其定义的基本概述如下
template<> 返回类型 函数名 [<类型实参表>](函数参数表)
{
}

例子

#include<iostream>
using namespace std;
template<class Ex>
Ex Greater(Ex x, Ex y);

template<> double Greater<double>(double,double);  #特化声明

int main(void)
{
	int intX=1,intY=2;
	double dblx = 3.0, dbly = 2.5;
	cout<<Greater(intX,intY)<<endl;
	cout<<Greater(dblx,dbly)<<endl;
	return 0;
}
template<class Ex>
Ex Greater(Ex x, Ex y)
{
	return x>y?x:y;
}
template<> double Greater(double x , double y)
{
	return x+y;
}
  1. 重载,函数模板支持重载,既可以在模板之间重载,又可以在模板和普通函数间重载,但模板函数的重载相比普通函数的重载要复杂一些。重载的普通函数如下
char* Greater(char* x, char * y)
{
	return (strcmp(x,y)>0?x:y);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章