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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章