C 認識模版函式

2021-07-12 05:11:24 字數 668 閱讀 2815

模板是泛型程式設計的基礎。所謂泛型程式設計就是編寫與型別無關的邏輯**,是一種復用的方式。模板分為模板函式和模板類。

首先,我們不使用模版函式,該函式用來實現比較兩個數是否相等。

bool isequal(int left, int right)//--->int型

bool isequal(const string& left, const string& right)//-->string型

若直接這樣實現,我們可以看出,兩者不同型別我們就要實現兩次,而這樣的**相似度又很高,就是說冗餘的**會使得編譯器不易維護。

下面,我們來看乙個模版函式,就可以避免這樣的問題。

#includeusing namespace std;

#includetemplate bool isequal(const t& left, const t& right)

templatebool isequal(const t1& left,const t2& right)

bool isequal(const string& left, const string& right)

void test()

本文出自 「han jing's blog」 部落格,請務必保留此出處

C 模版函式

implement strcmp like generic compare function returns 0 if the values are equal,1 if v1 is larger,1 if v1 is smaller template 模版形參表 int compare const...

C 模版函式

c 模版函式 定義方式 template知識點 template是 定義模板函式的關鍵字 template後面的尖括號不能省略 typename 或class 是宣告資料型別引數識別符號的關鍵字,用以說明它後面的標 識符是資料型別識別符號。這樣,在以後定義的這個函式中,凡希望根據實參資料型別來確定資...

c 模版函式

可以使用class或者typename欄位來申明 template template使用函式模版可以達到過載的目的,針對引數型別不同但函式實現一致的情況。include using namespace std namespace tmp 函式模版 t1和t2代表兩種不同的資料型別 template ...