C++函數(shù)模板的使用詳解
函數(shù)模板可以適用泛型來定義函數(shù),其中泛型可以是(int, double, float)等替換。在函數(shù)重載過程中,通過將類型作為參數(shù)傳遞給模板,可使編譯器自動(dòng)產(chǎn)生該類型的函數(shù)。
工作原理:比如需要定義一個(gè)比大小的max函數(shù),有三種類型的數(shù)據(jù)(int,double,float),可能就需要編寫三個(gè)函數(shù),這樣既浪費(fèi)時(shí)間,且容易出錯(cuò)。如:
#include <iostream> using namespace std; int Max(int a, int b); double Max(double x, double y); float Max(float s, float t); int main() { cout << Max(1, 2) << endl; cout << Max(3.0, 4.0) << endl; cout << Max(5.23, 5.24) << endl; return 0; } int Max(int a, int b) { return a > b ? a : b; } double Max(double x, double y) { return x > y ? x : y; } float Max(float s, float t) { return s > t ? s : t; }
結(jié)果如下:
從上面就可以看出一個(gè)很簡(jiǎn)單的比較大小的函數(shù),居然寫的這么繁瑣,顯然增加了工作量,極大降低了工作效率,因此,函數(shù)模板的出現(xiàn)十分有效的解決了這個(gè)問題。函數(shù)模板允許以任意類型的方式定義函數(shù),有兩種形式例如:
形式1:
template <typename Anytype> //template是函數(shù)模板的關(guān)鍵字 void Swap(Anytype &a,Anytype &b) { Anytype temp; temp=a; a=b; b=temp; }
形式2:
template <class Anytype> //class是函數(shù)模板的關(guān)鍵字 void Swap(Anytype &a,Anytype &b) { Anytype temp; temp=a; a=b; b=temp; }
使用函數(shù)模板之后的代碼如下:
形式1 :
#include <iostream> using namespace std; template <typename T> T Max(T a, T b); /* double Max(double x, double y); float Max(float s, float t); */ int main() { cout << Max(1, 2) << endl; cout << Max(3.0, 4.0) << endl; cout << Max(5.23, 5.24) << endl; return 0; } template <typename T> T Max(T a, T b) { return a > b ? a : b; }
形式2:
#include <iostream> using namespace std; template <class T> T Max(T a, T b); int main() { cout << Max(1, 2) << endl; cout << Max(3.0, 4.0) << endl; cout << Max(5.23, 5.24) << endl; return 0; } template <class T> T Max(T a, T b) { return a > b ? a : b; }
結(jié)果如下:
對(duì)比之下,明顯精簡(jiǎn)了很多。
到此這篇關(guān)于C++函數(shù)模板的使用詳解的文章就介紹到這了,更多相關(guān)C++函數(shù)模板內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言詳細(xì)分析常見字符串函數(shù)與模擬實(shí)現(xiàn)
字符串函數(shù)(String?processing?function)也叫字符串處理函數(shù),指的是編程語言中用來進(jìn)行字符串處理的函數(shù),如C,pascal,Visual以及LotusScript中進(jìn)行字符串拷貝,計(jì)算長度,字符查找等的函數(shù)2022-03-03C語言標(biāo)準(zhǔn)庫<math.h>和<setjmp.h>的實(shí)現(xiàn)
本文主要介紹了C語言標(biāo)準(zhǔn)庫<math.h>和<setjmp.h>的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11Qt實(shí)現(xiàn)字幕無間隙滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了如何利用Qt實(shí)現(xiàn)字幕無間隙滾動(dòng)效果,文中的實(shí)現(xiàn)過程講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-11-11