模板包括函數模板和類模板
模板可以實現泛型編程
template <typename/class T>
T disp(T &a, T &b){}
函數模板
注意事項:
- 自動類型推導,必須推導出一致的數據類型T,纔可以使用
- 模板必須要確定出T的數據類型,纔可以使用
#include <iostream>
using namespace std;
template <typename T>
void myswap(T &a, T &b){
T temp = a;
a = b;
b = temp;
}
int main(){
int a = 10, b = 20;
myswap<int>(a, b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
return 0;
}
普通函數與函數模板的區別
- 普通函數調用時可以發生自動類型轉換(隱式類型轉換)
- 函數模板調用時,如果利用自動類型推導,不會發生隱式類型轉換
- 如果利用顯示指定類型,可以發生隱式類型轉換
/*
不同數據類型數組進行排序
排序規則從大到小,排序算法爲選擇排序
分別利用char數組和int數組進行測試
*/
#include <iostream>
using namespace std;
template <typename T>
void myswap(T &a, T &b){
T temp = a;
a = b;
b = temp;
}
template <typename T>
void mysort(T arr[], int n){
int temp;
for(int i = 0; i < n; i++){
temp = i;
for(int j = i; j < n; j++){
if(arr[j] > arr[temp]) temp = j;
}
myswap(arr[i], arr[temp]);
}
}
int main(){
int arr[]={5,3,2,4,1};
char brr[]={'b','c','a','d'};
mysort(brr, 4);
for(int i = 0; i < 4; i++){
cout<<brr[i]<<" ";
}
cout<<endl;
return 0;
}