C++ 模板template

模板template

  • 模板是對具有相同特性的函數或類的再抽象,模板是一種參數多態性的工具,可以爲邏輯功能相同而類型不同的程序提供一種代碼共享的機制。
  • 一個模板並非一個實實在在的函數或類,僅僅是一個函數或類的描述,是參數化的函數和類

類型: 函數模板和類模板

  • 抽象:
    • 變量→類型
    • 對象→類
    • 函數→函數模板
    • 類→類模板
      在這裏插入圖片描述

函數模板

template <class T1, class T2,> 
//==============================================
返回類型 functionName(參數表){
   	//函數模板定義體
}
// 也可以使用 typename替代class
template <typename T1,typename T2,>
//==============================================

template <class T>
T max (T a, T b) 
{ 
	return a>b ? a : b;
}
int i = max (3, 4);
char ch = max (‘a’, ‘A’);
float f = max (5.0, 1.0);

類模板

template<class T1,class T2,int T3>

類模板的成員函數的定義
方法1:在類模板外定義,語法
template <模板參數列表> 
返回值類型 類模板名<模板參數名錶>::成員函數名 (參數列表)
	{。。。};
// ==================================================
#include<iostream>
#include<string>
using namespace std;
const int Size=5;       				
template<class T>
class Array{
private:
		T a[Size];
public:
		Array() { for(int i=0;i<Size;i++) 	a[i]=0; }  			
		T &operator[](int i);                     								
		void Sort(); 
};

template<class T>  
T& Array<T>::operator[](int i) {
		if(i<0||i>Size-1){
			cout<<"\n數組下標越界!\n";
			exit(1);
		}
		return a[i];
}

template<class T>  
void Array<T>::Sort(){
		for(int i=0;i<Size-1;i++){
			int p=i;
			for(int j=i+1;j<Size;j++)
				if(a[p]<a[j]) p=j;
			T t=a[p];	a[p]=a[i];	a[i]=t;
		}
}

特化

template <> 返回類型 類模板名<特化的數據類型>::特化成員函數名(參數表){
   …… 								//函數定義體
}
// ========================================================

template<>  
void Array<char *>::Sort(){
		for(int i=0;i<Size-1;i++){
			int p=i;
			for(int j=i+1;j<Size;j++)
				if(strcmp(a[p],a[j])<0)
					p=j;
			char* t=a[p];
			a[p]=a[i];
			a[i]=t;
		}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章