自定義模板

規則:不管是函數末班還是類模板,在證明或定義時,只能在全局命名空間或類範圍內進行,不能在局部範圍內,不能在函數內(包括main函數)聲明或定義一個模板。

模板定義完成後,使用時需要進行實例化操作,編譯器在編譯時會確認模板參數具體時間哪種類型的,這個過程稱爲模板的實力化

函數模板的標準定義如下:

template<typename 形參名1,typename形參名2,...>
返回類型 函數名
{
    函數體
}

以下3個函數可以用一個函數模板來實現

char max(const char &a,const char &b,const char &c)
{
	char temp=(a>b)?a:b;
	return (temp>c)?temp:c;	
} 
int max(const int &a,const int &b,const int &c)
{
	char temp=(a>b)?a:b;
	return (temp>c)?temp:c;	
} 
double max(const double &a,const double &b,const double &c)
{
	char temp=(a>b)?a:b;
	return (temp>c)?temp:c;	
} 

3個重載函數的算法邏輯完全相同,只不過是輸入輸出的數據類型不同而已,代碼的冗餘度比較高

函數模板

template<typename T>

T max(const T&a,const T &b,const T &c)
{
	char temp=(a>b)?a:b;
	return (temp>c)?temp:c;	
} 

函數模板實力化

int main()
{
	int a=10;
	int b=22;
	int c=15;
	cout<<max('a','b','c')<<endl;
	cout<<max(a,b,c)<<endl;
	cout<<max(55.55,66.66,33.33)<<endl;
	return 0;
}

還有其他的一些函數模板

template<typename T> void 函數名(T a[],int n,bool type)
{
	函數體; 
}

類模板

template<typename 形參名1,typename 形參名2,...>
返回類型 類名<形參名1 ,形參名2,...>::成員函數名(形參列表)
{
	//
 } ;

類模板的實現如下
template<typename T,unsigned int N>
class Stack
{
	private:
		unsigned int index;
		T a[N];
	public:
		Stack();index(){}
		bool push(const T&valude);
		bool pop(T &value);
		bool full(){return index==N;}
		bool empty(){return index==0;}
		unsigned int size(){return index;}
		unsigned canacity(){return N;}
 } ;


template<typename T,unsigned int N> bool Stack<T,N>::push(const T&value)
{
	if((index<N-1)&&(index>=0))
	{
		a[index++]=value;
		retur true;
	}
	else
	{
		return false;
	}
}
template<typename T,unsigned int N> bool Stack<T,N>::pop(T&value)
{
	if(index==0)
	{
		
		retur false;
	}
	else
	{
		value=a[--index];
		return false;
	}
}
實例化
Stack<int ,20>a;//將Stack類模板實例化爲佔空間深度爲20,站操作數類型爲int 的類,然後在實例化對象a

Stack<char,12>ch;

Stack<float,8>f;

Stack<string,10>s;

發佈了50 篇原創文章 · 獲贊 76 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章