C++的函數(shù)和模板函數(shù)

字號:

在c++沒有模板(template)機制的時候,我們使用的就是普通的函數(shù),我們要實現(xiàn)一個加法函數(shù),他能夠?qū)蓚€參數(shù)求和,并根據(jù)參數(shù)的類型返回具有適當(dāng)類型的值,就必須手工書寫所有的代碼:
    short sum(short a,short b) {return a+b;}
    int sum(int a,int b){return a+b;}
    float sum(float a,float b){ return a+b;}
    ……
    非常麻煩,可以用c++的模板函數(shù)來表達“通用型的函數(shù)”
    template
    T sum(T a,T b)
    {
     return a+b;
    }
    保存為sumtest.h
    現(xiàn)在,c++編譯器可以根據(jù)我們調(diào)用sum函數(shù)的參數(shù)類型“現(xiàn)場”生成一個適當(dāng)?shù)暮瘮?shù),然后調(diào)用它。例如:
    #include
    #include “sumtest.h”
    using namespace std;
     int main(void)
    {
     float fa=1,fb=3,fs;
     fs=sum(fa,fb);
     cout<<”sum(float,float) 1and 3=”<    }
    [root@localhost html]# g++ -o sumtest sumtest.cpp
    [root@localhost html]# ./sumtest
    sum(float,float) 1 and 3=4
    看上面的代碼,c++編譯器為我們生成一個“float版本”的sum函數(shù)并調(diào)用它。如果我們給出的參數(shù)類型不一樣,則編譯器會報錯。例如
    #include
    #include "sumtest.h"
    using namespace std;
    int main(void)
    {
     float fa=1,fs;
     int Ib=3;
     fs=sum(fa,Ib);
     cout<<"sum(float,Int) 1 and 3="<     return 0;
    }
    [root@localhost html]# g++ -o sumtest sumtest.cpp
    sumtest.cpp: In function `int main ()’:
    sumtest.cpp:10: no matching function for call to `sum (float &, int
    &)’
    由于函數(shù)模板并不支持兩個不同類型的參數(shù)求和,所以C++編譯器會報告無法生成真正的函數(shù),從而讓程序員有機會知道調(diào)用參數(shù)除了問題。
    如果不是用模板函數(shù)而用普通函數(shù),即使參數(shù)類型不完全一致也可能會通過編譯。例如
    #include
    using namespace std;
    float sum(float a,float b)
    {
     return a+b;
    }
    int main(void)
    {
     float fa=1,fs;
     int Ib=3;
     fs=sum(fa,Ib);
     cout<<"sum(float,Int) 1 and 3="<     return 0;
    }
    [root@localhost html]# g++ -o sumtest sumtest.cpp
    [root@localhost html]# ./sumtest1
    sum(float,Int) 1 and 3=4
    因為c++中,int類型可以自動轉(zhuǎn)換成float類型,于是這種情況下不會報錯。
    函數(shù)模板不是真正的函數(shù),它只是c++編譯器生成具體函數(shù)的一個模子。所以不能把函數(shù)模板的聲明和定義分開放在不同的文件中,而普通的函數(shù)可以這樣做。
    C++函數(shù)還有一個問題就是和c的函數(shù)的區(qū)別。最近在www.chinaunix.net C/C++論壇上出現(xiàn)了幾個關(guān)于c語言寫的代碼,c編譯器可以通過編譯,采用c++編譯器就不行了。就是這個問題。