C 基礎 C 模板(Template)簡介

2022-07-29 19:15:17 字數 2002 閱讀 7570

1、概述:

模板(template)是一種強大的c++軟體復用特性,通常有兩種形式:函式模板和類模板。函式模板針對僅引數型別不同的函式;類模板針對僅資料成員和成員函式型別不同的類。函式模板和類模板可以是程式設計師只需制定乙個單獨的**段,就可表示一整套稱為函式模板特化的相關(過載)函式或是表示一整套稱為類模板特化的相關的類。這種技術稱為泛型程式設計(generic programming)。

使用模板的好處在於,可以使程式設計師編寫與型別無關的**。使用時要注意:模板的宣告或定義只能在全域性,命名空間或類範圍內進行。即不能在區域性範圍,函式內進行,比如不能在main函式中宣告或定義乙個模板。

模板定義以關鍵字template開始,後接模板形參表,模板形參表是用尖括號括住的乙個或者多個模板形參的列表,形參之間以逗號分隔。模板形參可以是表示型別的型別形參,也可以是表示常量表示式的非型別形參。非型別形參跟在型別說明符之後宣告。型別形參跟在關鍵字class或typename之後定義。

2、函式模板

函式模板格式如下:

template函式名(引數列表)

或 template函式名(引數列表)

其中尖括號內為模板形參列表,不能為空,但具體數目依需要而定。此處,typename和class關鍵字無區別。以下以一段**示例簡要說明使用。

/*

test for template

*/#includeusing namespace std;

templatet findbigger(t &a, t &b)

void main()

或 templateclass 類名

依然以**說明,定義了堆疊類stack及其操作,並建立模板函式類測試。

//stack class template

//filename: stack.h

#ifndef stack_h

#define stack_h

templateclass stack

bool push(const t &); //push an element onto the stack

bool pop(t &);//pop an element off the stack

bool isempty() const

bool isfull() const };

templatestack::stack(int n):size(n>0 ? n:10),top(-1),stackptr(new t[size])

templatebool stack::push(const t &value)

return false;

}templatebool stack::pop(t &value)

return false;

}#endif

/*

test for template

*///filename: templatetest.cpp

#include#include#include"stack.h"

using namespace std;

//建立模板函式來測試

templatevoid teststack( stack&thestack, t value, t increment ,const string stackname)

結果截圖:

幾點說明:

template//其中elements就是非型別引數,然後使用如下宣告:

stackdoublestack; 例項化乙個有100個double元素的doublestack物件。

template//stack元素預設為string物件,然後可以使用如下宣告:

stack< >stringstack; 來例項化乙個string型別的stack。

C 類模板template

類模板 對於功能相同而資料型別不同的一些函式,可以定義乙個可對任何型別變數進行操作的函式模板,在呼叫函式時,系統會根據實參的型別,取代函式模板中的型別引數,得到具體的函式 includeusing namespace std template class compare numtype max nu...

C 類模板 template

類模板與函式模板的定義和使用類似。有時,有兩個或多個類,其功能是相同的,僅僅是資料型別不同,如下面語句宣告了乙個類 class compare int intmax intmin private int x,y 其作用是對兩個整數作比較,可以通過呼叫成員函式max和min得到兩個整數中的大者和小者。...

C 類模板 template

類模板與函式模板的定義和使用類似。有時,有兩個或多個類,其功能是相同的,僅僅是資料型別不同,如下面語句宣告了乙個類 class compare int intmax intmin private int x,y 其作用是對兩個整數作比較,可以通過呼叫成員函式max和min得到兩個整數中的大者和小者。...