C 函式模板

2021-09-06 15:21:57 字數 2986 閱讀 6346

函式模板提供了一種函式行為,該函式行為可以用多種不同的型別進行呼叫,也就是說,函式模板代表乙個函式家族,這些函式的元素是未定的,在使用的時候被引數化。

下面舉乙個簡單的例子:

templateinline t 

const& max(t const& a, t const&b)

這個模板定義指定了乙個「返回兩個值中最大者」的函式家族,這兩個值通過函式引數a , b傳遞給函式模板的,而引數的型別還沒有確定,用模板引數t來代替。

其中,typename可以用class來代替,但是建議使用typename

完整**如下:

#include#include

using

namespace

std;

template

inline t

const& max(t const& a, t const&b)

intmain()

模板引數可以根據我們傳遞的實參來決定,如果我們傳遞了兩個int給引數型別t const&,那麼c++編譯器得出結論:每個t都必須正確的匹配,如果此時傳遞的實參為:max(4, 4.2),則出現編譯錯誤

有3種方法來處理上面的錯誤:

1、對實參進行強制型別轉換,使它們可以互相匹配:

max(static_cast(4), 4.2);

2、顯示指定(或限定)t的型別:

max(4, 4.2)

3、指定兩個引數可以具有不同的型別

函式模板有2種型別的引數:

1、模板引數:位於函式模板名稱的前面,在一對尖括號內部進行宣告:

template

2、用引數:位於函式模板名稱之後,在一對圓括號內部進行宣告:

...max(t const& a, t const& b)

可以宣告任意數量的模板引數,在函式模板的內部,不能指定預設的引數。

templateinline t1 max(t1 

const& a, t2 const&b)

...max(

4, 4.2);

可以引入第三個模板實參型別,來定義函式模板的返回型別:

templateinline rt max(t1 

const& a, t2 const&b);

...max

(4, 4.2);

行得通,但是很麻煩

還有一種方法是只顯示的指定第乙個實參,而讓演繹過程推導出其餘的實參。

templateinline rt max(t1 

const& a, t2 const&b);

...max

(1, 4.2); //

ok, 返回型別是double

和普通函式一樣,函式模板也可以被過載,示例**如下:

#include#include

using

namespace

std;

inline

intconst& max(int

const& a, int

const&b)

template

inline t

const& max(t const& a, t const&b)

template

inline t

const& max(t const& a, t const& b, t const&c)

intmain()

下面的更有用的例子將會為指標和普通的c字串過載這個求最大值的模板:

#include#include

using

namespace

std;

//求兩個任意型別值的最大者

templateinline t

const& max(t const& a, t const&b)

//求兩個指標所指向值的最大者

templateinline t* const& max(t* const& a, t* const&b)

//求兩個c字串的最大者

inline char

const* const& max(char

const* const& a, char

const* const&b)

intmain()

以上在所有實現過載裡面,都是通過引用來傳遞每個例項的,但是一般而言,在過載函式模板的時候,最好只是改變那些需要改變的內容,應該把改變限制在以下兩個方面:

改變引數的數目或顯式地指定模板引數

對於以上的過載,如果改為基於c-string的max()函式,通過傳值來傳遞引數,就不能實現3個引數的max()版本:

#include#include

using

namespace

std;

//求兩個任意型別值的最大者(通過傳引用進行呼叫)

templateinline t

const& max(t const& a, t const&b)

//求兩個c字串的最大者(通過傳值進行呼叫)

inline char

const* max(char

const* a, char

const*b)

//求3個任意型別值的最大者(通過傳引用進行呼叫)

templateinline t

const& max(t const& a, t const& b, t const&c)

intmain()

錯誤在於:如果對3個c-string呼叫max,則語句return max(max(a, b), c);將產生錯誤

原因是對於c-string而言,max(a, b)產生了乙個新的臨時區域性值,該值有可能被外面的max函式以傳引用的方式返回,將導致傳回無效的引用。

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