C 函式模板

2021-07-10 20:57:21 字數 1458 閱讀 8966

01_函式模板定義.cpp

#include

#include

using

namespace

std;

#if 0

int max(int a,int b)

char max(char a,char b)

double max(double a,double b)

#endif

//#define max(type1 a, type1 b)

//template

template

t max(t a, t b)

int main()

int main()

template

<>

int max(int a,int b)

int main()

04_函式模板的過載發生歧義.cpp

#include

#include

using

namespace

std;

//函式模板的過載,匹配規則:

//1,對於乙個函式呼叫,其候選函式包括所有的函式模板實參推斷成功而匯出的函式例項;

//2,模板和非模板都是按型別順序來轉換;

//3,如果有乙個函式提高的比其他函式都好的匹配,那麼選擇此函式:

//a:如果同樣好的函式只有乙個是非模板的函式,則選擇此函式;

//b:如果同樣好的函式中沒有非模板函式,而有多個模板函式,且其中乙個模板比其他模板更特例化,則選擇此模板;

//c:否則,此函式呼叫發生歧義!

template

t max(t a, t b)

template

m max(m a,m b)

int main()

05_函式模板的特例化.cpp

#include

#include

using

namespace

std;

//函式模板的過載,匹配規則:

//1,對於乙個函式呼叫,其候選函式包括所有的函式模板實參推斷成功而匯出的函式例項;

//2,模板和非模板都是按型別順序來轉換;

//3,如果有乙個函式提高的比其他函式都好的匹配,那麼選擇此函式:

//a:如果同樣好的函式只有乙個是非模板的函式,則選擇此函式;

//b:如果同樣好的函式中沒有非模板函式,而有多個模板函式,且其中乙個模板比其他模板更特例化,則選擇此模板;

//c:否則,此函式呼叫發生歧義!

template

t max(t a, t b)

//int max(int a,int b, int c)

int max(int a,int b)

int main()

c 函式模板

include using namespace std template t max t a,t b,t c int main int main int i1 185,i2 76,i3 567,i double d1 56.63,d2 90.23,d3 3214.78,d long g1 67854...

c 函式模板

關鍵字template總是放在模板的電腦關於與宣告的最前面,關鍵字後面是用逗號分隔的模板參數列,該列表是模板參數列,不能為空。模板引數可以是乙個模板型別引數,它代表了一種型別 也可以是乙個模板非型別引數,它代表了乙個常量表示式。模板型別引數由關鍵字class或typename後加乙個識別符號構成。在...

C 函式模板

c 提供了函式模板 function template 所謂函式模板,實際上是建立乙個通用函式,其函式型別和形參型別不具體指定,用乙個虛擬的型別來代表。這個通用函式就稱為函式模板。凡是函式體相同的函式都可以用這個模板來代替,不必定義多個函式,只需在模板中定義一次即可。在呼叫函式時系統會根據實參的型別...