c++學習(函數模板, 類模板)

函數模板

  模板形參不能爲空。一但聲明瞭模板函數就可以用模板函數的形參名聲明類中的成員變量和成員函數,即可以在該函數中使用內置類型的地方都可以使用模板形參名,聲明瞭形參,而沒有使用,會不通過編譯。額我的是這樣
template <typename T>
or  template <class T>

template 與 <> 之間必須無其他內容。
DEMO

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
template <typename id>
id func(id a, id b)
{
    if(a > b)
        return a;
    else return b;
}
//double func(double a,double b){
//    if(a > b) return a;
//    else return b;
//}
int main()
{
    int a = 1;
    double b = 2;
    int c = func(a, b);
    cout<<c<<endl;
   return 0;
}

注意 :
1. template 中可以有多個形參,但是 形參不可以重名
2. 模板類型形參跟一般的形參類似,具有屏蔽外圍變量類型的作用: template 假如 id 是我們之前聲明的變量,那麼 會被覆蓋。

typedef double id;
template <typename id>
id func(id a, id b)
{
//a is not a double value;
    if(a > b)
        return a;
    else return b;
}

3.模板函數不會提供隱式類型轉換
上面的例子是錯誤的,把註釋釋放就可以了
4.函數調用順序
When our program is running, it will find the function which is match our program completely at first.If it can’t find that function,it will find the function template, and the function template’s parameters must be same with the our pargram’s function.if it can’t find the template’s neither.it will find the function which has the same name , and do the compulsory type conversion.
5 模板參數不必都是類型,我們也可以定義非類型模板形參
具體看不同參考 http://bbs.csdn.net/topics/390207445

template <typename T,int N>
void func(const T (&parm)[N])
{
    for(int i = 0;i != N ; i++)
        cout<<parm[i]<<endl;
}

6.模板的形參使用const引用。因爲使用引用,可以避免那些不能複製的類型不能調用模板(比如流),而且如果調用模板的對象比較大,那麼可以省去複製的代價。

//輸出到流  
template <typename T1,typename T2>  
T1& print(T1& s,T2 val)  
{  
    s<<val<<endl;  
    return s;  
}  

那麼可以使用它向任意流中輸出內容:
如果不懂ostringstram等
請看http://blog.csdn.net/qq1987924/article/details/7671154

double dval = 0.88;  
float fval = -12.3;  
string oristr = "this is a test",desstr;  
ostringstream oss(desstr);  
ofstream outFile("result.dat");  
print(cout,-3);  
print(cout,dval);  
print(cout,oristr);  
print(outFile,-3);  
print(outFile,dval);  
print(outFile,fval);  
print(outFile,oristr);  
print(oss,-3);  
print(oss,dval);  
print(oss,fval);  
print(oss,oristr);  
cout<<oss.str()<<endl;  

而const則意味着你可以用常量調用這個函數:當沒有const時:

template <typename T>  
int big(T &a,T &b)  
{  
    if (a>b)  
        return 1;  
    if (a<b)  
        return 0;  
}  

你只能使用:

[cpp] view plaincopy
int m = 1;  
int n = 2;  
cout<<big(m,n)<<endl;  

而如果加上const:int big(const T &a,const T &b)那麼就可以: cout<

發佈了448 篇原創文章 · 獲贊 3 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章