C++模板-29-什麼是模板和一個簡單的例子

這篇開始進入模板的學習,接下來要學習模板,各種函數模板和類模板,然後學習幾個標準的類,例如string類的,然後過度到學習各種容器。

 

1.什麼是模板

模板就是建立通用模具,大大提高代碼複用性。

 

2.沒有模板是什麼樣的

例如,我們來做這個小練習,交換兩個數的值,例如有兩個int類型交換,兩個float類型交換。由於前面的知識,代碼大概是這樣去寫。

#include <iostream>
using namespace std;

void SwapInt(int &a, int &b)
{
    int tem = a;
    a = b;
    b = tem;
}

void SwapFloat(float &c, float &d)
{
    float tem = c;
    c = d;
    d = tem;
}

void test01()
{
    int a = 10;
    int b = 20;
    SwapInt(a, b);
    cout << "a= " << a << endl;
    cout << "b= " << b << endl;

    float c = 1.1;
    float d = 2.2;
    SwapFloat(c, d);
    cout << "c= " << c << endl;
    cout << "d= " << d << endl;

}

int main()
{
    test01();
    system("pause");
    return 0;
}

注意上面交換傳的參數是引用,不是具體的數值。

測試運行結果

結果肯定沒有問題,兩個數交換過來了。如果我們要繼續交換兩個字符,或者double類型,或者兩個字符串,那麼我們還需要寫很多重複的代碼。

 

3.模板簡化了代碼

下面用模板的思想來優化代碼

#include <iostream>
using namespace std;

template <typename T>
void Swap(T &a, T &b)
{
    T tem = a;
    a = b;
    b = tem;
}


void test01()
{
    int a = 10;
    int b = 20;
    Swap(a, b);
    cout << "a= " << a << endl;
    cout << "b= " << b << endl;

    float c = 1.1;
    float d = 2.2;
    Swap(c, d);
    cout << "c= " << c << endl;
    cout << "d= " << d << endl;

}

int main()
{
    test01();
    system("pause");
    return 0;
}

重點就在Swap()方法中,在方法定義上面一行,template <typename T>, 這是固定寫法,其中template 和typename是關鍵字,T可以隨便寫成其他字母,一般習慣T表示模板的首字母。

運行結果一樣,都產生了交換。寫一個方法,可以適應全部類型的兩個相同類型參數的值進行交換。這是一個函數模板。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章