函數模板->模板函數

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

/**
 * 定義模板函數exchange
 * 實現功能:交換兩個數的位置
 * -------------------------------------
 * 定義函數模板的時候確定需要幾個變量,幾個常量.
 * 變量由 typename 或者 class 聲明,但沒有指明類型
 * 常量聲明的時候必須確定類型,在編譯的時候被看做常量處理.
 * 在使用模板函數的時候,必須依次指明需要的數據類型,用 "< >" 括起來, 常量也必須明確指明所對應的類型的一個值.
 * 調用模板函數的時候, < > 中的類型內容,與聲明函數模板的時候相同,如:
 * template<class C, int Ksize>
 * display<string, 5>("hello world.");
 */
template<typename T>
void exchange(T a, T b)
{
    T temp = a;
    a = b;
    b = temp;
}
template<typename T, typename S>
void display(T t, S s)
{
    cout << t << endl;
    cout << s << endl;
}

template<class C, int Ksize>
void display(C Str)
{
    for (int i=0; i<Ksize; ++i)
    {
        cout << Str << endl;
    }
}
int main(void)
{
    int x = 10;
    int y = 20;
    // 調用模板函數
    exchange<int>(x,y);
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;

    display<char, double>('h', 3.14);
    display<string, 5>("hello world."); //打印5行string類型的"hello world."
    
    return 0;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容