C++函數模板簡介

來源:互聯網
上載者:User

標籤:ror   簡介   pre   log   call   summary   div   span   ext   

函數模板(function template):

定義:函數模板不是一個實在的函數,編譯器不能為其產生可執行代碼。定義函數模板後只是一個對函數功能架構的描述,當它具體執行時,將根據傳遞的實際參數決定其功能。

格式:template <class 型別參數1,class 型別參數2,...>

 樣本:

template <class T>T Inc(T n) {    return 1 + n;}

? 不通過參數執行個體化函數模板

   cout << Inc<double>(4) / 2; //輸出:2.5 

? 函數模板可以重載,只要它們的形參表或型別參數表不同即可。? 函數模板和函數的次序  在多個函數和函數模板名字相同的情況下,編譯器如下處理一條函數調用語句:  1)  先找參數完全符合的普通函數(非由模板執行個體化而得到的函數)。  2)  再找參數完全符合的模板函數。  3)  再找實參經過自動類型轉換後能夠匹配的普通函數。  4)  上面的都找不到,則報錯  
template <class T>T Max(T a, T b) {    cout << "TemplateMax" << endl;     return 0;}template <class T, class T2>T Max(T a, T2 b) {    cout << "TemplateMax2" << endl;    return 0;}double Max(double a, double b) {    cout << "MyMax" << endl;    return 0;}int main(void){    int i=4,j=5;    Max(1.2,3.4);    //output:MyMax    Max(i,j);    //output:TemplateMax    Max(1.2,3);    //output:TemplateMax2    return 0;}

? 匹配函數模板時,不進行類型自動轉換

template <class T>T myFunction(T arg1, T arg2) {    cout << arg1 <<" "<< arg2 << endl;    return arg1;}...myFunction(5,8.5);    //error, no matching function for call to ‘myFunction(int, double)‘

 ? 函數模板樣本:Map

  實現把一個數組的某一段指定序列按照自訂類型轉換規則轉換後存到另一數組中。

  

 1 #include <iostream> 2 using namespace std; 3 template <class T, class Pred> 4 void Map(T s, T e, T x, Pred op) { 5     for(; s != e; ++s, ++x) { 6         *x = op(*s); 7     } 8 } 9 double Square(double x) {10     return x*x;11 }12 int main(void) {13     int a[5] = {1,2,3,4,5}, b[5];14     Map(a, a+5, b, Square);15     for(int i=0; i<5; i++) {16         cout << b[i] <<ends;17     }18     return 0;19 }

執行Map(a, a+5, b, Square); 後,執行個體化以下函數:

  void Map(int * s, int * e, int * x, double (*op)(double)) {
    for(; s != e; ++s, ++x) {
    *x = op(*s);
    }
  }

將a[]中的元素平方後存入b[]中。

 

 

 2018-01-24

 

 

 

 

 

 

 


C++函數模板簡介

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.