閱讀823 返回首頁    go 阿裏雲 go 技術社區[雲棲]


第六章 C++模板

//------------------------第六章 模板----------------------------------------------
/*
  模板是實現代碼重用機製的一種工具,可以實現類型參數化。模板分為函數模板和類模板。
  C++中不建議使用宏,因為宏避開了類型檢查機製,容易造成不必要的錯誤。
  模板聲明形式:
  template <class Type> //class可以換成typename
  返回類型 函數名(模板參數表)
  {
      函數體
  }
*/
#include <iostream>
#include <cstring>
using namespace std;

template <typename Type>
Type GetMax(Type lhs, Type rhs)
{
    return lhs > rhs ? lhs : rhs;
}

int main()
{
    int nLhs = 10, nRhs = 90;
    float fLhs = 10.2, fRhs = 21.2;
    double dLhs = 2.11, dRhs = 0.123;
    char cLhs = 'b', cRhs = 'a';

    cout << GetMax(nLhs, nRhs) << endl
         << GetMax(fLhs, fRhs) << endl
         << GetMax(dLhs, dRhs) << endl
         << GetMax(cLhs, cRhs) << endl;
    return 0;
}


#include <iostream>
#include <cstring>
using namespace std;

template <typename Type>
Type Sum(Type *pArray, int size = 0)
{
    Type total = 0;

    for (int i = 0; i < size; i++)
        total += pArray[i];

    return total;
}

int main()
{
    int nArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    double dArray[] = {1.1, 2.2, 3.3, 4.4};

    cout << Sum(nArray, 9) << endl;//output 45
    cout << Sum(dArray, 4) << endl;//output 11

    return 0;
}


#include <iostream>
#include <cstring>
using namespace std;

//template <typename T>與函數模板定義語句之間不允許有別的語句
//int i; //這裏出錯,不允許
//T sum(T in);
//不過可以同時多個類型

template <typename T1, typename T2>
void OutputData(T1 lhs, T2 rhs)
{
    cout << lhs << " " << rhs << endl;
}

int main()
{
    OutputData('a', "b");
    OutputData(1, 2);
    OutputData(1, 1.9);
    return 0;
}


#include <iostream>
#include <cstring>
using namespace std;

template <typename T>
T Max(T lhs, T rhs)
{
    return lhs > rhs ? lhs : rhs;
}
int Max(int lhs, int rhs)//課本上隻寫int Max(int, int);但不能通過,必須要有定義
{
    return lhs > rhs ? lhs : rhs;
}

int main()
{
    int i = 10;
    char c = 'a';

    Max(i, i);//正確調用
    Max(c, c);//正確調用

    //解決辦法可以是再重載一個普通函數,不需要模板函數,並且要
    //同名,加上int Max(int i, char c)就對了
    cout << Max(i, c) << endl;//出錯,原來是模板函數不會進行隱式強製類型轉換
    cout << Max(c, i) << endl;//出錯,原來是模板函數不會進行隱式強製類型轉換
    return 0;
}
下麵會繼續更新--------------------------------------------------------------------------------------------------------------------- 


最後更新:2017-04-02 15:15:09

  上一篇:go 少年黑客艾倫與蓋茨
  下一篇:go 歡迎360支持手機毒霸 治理惡意廣告需要全行業努力