C 深度解析 45 函式模板的概念和意義

2021-09-25 12:53:22 字數 1434 閱讀 8835

1.發散性問題

2.程式設計實驗

#include #include using namespace std;

// 巨集定義**塊

#define swap(t, a, b)    \

do                       \

while (0) // 這裡不加這個分號; 可能是保證乙個整體,保證當做一條語句處理。

// 定義函式方式

void swap(int &a, int &b) // 引用就是常量指標

void swap(double &a, double &b) // 引用就是常量指標

void swap(string &a, string &b) //引用就是常量指標

int main()

定義函式c++中有沒有解決方案集合兩種方法的優點?泛型程式設計3.泛型程式設計

// swap函式的泛型寫法

void swap(t &a,t &b)

3.1c++中泛型程式設計 —函式模板

template //告訴編譯器開始泛型程式設計,t是乙個泛指型別

void swap(t &a,t &b)

函式模板的使用

3.2 程式設計實驗

#include #include using namespace std;

template //在函式前宣告

void swap(t &a, t &b)

template void selectsort(t a, int len)

} }}template void println(t a, int len)

cout << endl;

}int main();

println(a, 5);

selectsort(a, 5);

println(a, 5);

string s[5] = ;

println(s, 5);

selectsort(s, 5);

println(s, 5);

system("pause");

return 0;

}

4.小結

C 深度剖析教程35 函式模板的概念和意義

c 中有幾種變數交換的方法?定義巨集 塊和定義函式 include include using namespace std define swap t,a,b do while 0 void swap int a,int b void swap double a,double b void swap...

函式模板的概念和意義

發散性問題 c 中有幾種交換變數的方法?定義巨集 塊 vs 定義函式 程式設計實驗 include include using namespace std define swap t,a,b do while 0 int main 利用定義巨集 塊的方法看上去很完美,但是巨集是預處理器處理的程式單元...

C 函式模板和模板函式

函式模板可以用來建立乙個通用的函式,以支援多種不同的形參,避免了過載函式的多個函式體。它的最大特點是把函式使用的資料型別作為引數。函式模板的宣告形式為 template 返回型別 函式名 參數列 其中,template是定義模板函式的關鍵字 template後面的尖括號不能省略 例如 templat...