1. 程式人生 > 實用技巧 >C++面向物件入門(三十八)過載函式模板

C++面向物件入門(三十八)過載函式模板

函式模板存在的缺陷
1 無法支援自動型別轉換, 需要自動過載普通函式實現出現型別轉換時的功能
2 對於特定的資料型別的處理需要定義特殊的普通過載函式以保證功能的正確實現

程式碼示例:

#include <iostream>
using namespace std;

/*
函式模板存在的缺陷
1 無法支援自動型別轉換, 需要自動過載普通函式實現出現型別轉換時的功能
2 對於特定的資料型別的處理需要定義特殊的普通過載函式以保證功能的正確實現
*/

//定義函式模板max求最大值
template<typename T>
T max(T a, T b)
{
    return a > b ? a : b;
}

//將函式模板max擴充套件到求多個數的最大值 template<typename T> T max(T arr[], int len) { T max = arr[0]; for (int i = 1; i < len; i++) { max = max > arr[i] ? max : arr[i]; } return max; } //發現當前函式模板沒有普通傳值引數的型別轉換機制, 需額外定義普通函式過載函式模板 float max(int a, float b) { return a > b ? a : b; }
float max(float a, int b) { return a > b ? a : b; } double max(int a, double b) { return a > b ? a : b; } double max(double a, int b) { return a > b ? a : b; } //除了型別轉換機制外, 又是需要特別定義某種特定型別變數的函式邏輯, 需要使用特定的普通函式過載函式模板 //比如資料型別為只需char陣列的指標變數時, 預設比較大小, 比較的是兩個指標的地址大小(int型別) //而實際上我們要比較的是兩個字串的大小
//故需要使用特定的普通函式過載函式模板 //註釋下面函式後, 比較字串的功能達不到預期效果 char *max(char a[], char b[]) { return strcmp(a, b) > 0 ? a : b; } int arrLen = 0; //過載輸出長度大於等於arrLen的int陣列的的前六個元素 ostream &operator<<(ostream & cout, int *t) { for (size_t i = 0; i < arrLen; i++) { if (i) cout << " " << t[i]; else cout << t[i] ; } return cout; } //過載輸出長度大於等於arrLen的double陣列的的前六個元素 ostream &operator<<(ostream & cout, double *t) { for (size_t i = 0; i < arrLen; i++) { if (i) cout << " " << t[i]; else cout << t[i]; } return cout; } int main() { int i1, i2; i1 = 1; i2 = 2; cout << i1 << " and " << i2 << " max is " << max(i1, i2) << endl; double d1, d2; d1 = 9.0; d2 = 6.6; cout << d1 << " and " << d2 << " max is " << max(d1, d2) << endl; float f1, f2; f1 = (float)d1; f2 = (float)d2; cout << f1 << " and " << f2 << " max is " << max(f1, f2) << endl; cout << i1 << " and " << f2 << " max is " << max(i1, f2) << endl; cout << d1 << " and " << i2 << " max is " << max(d1, i2) << endl; int intArr[] = { 1,2,3,4,5,6 }; double doubleArr[] = { 1.1,2.2,3.3,4.4,5.5,6.6 }; //設定過載的<<運算子輸出陣列元素個數 arrLen = 6; cout << intArr << " max is " << max(intArr,6) << endl; cout << doubleArr << " max is " << max(doubleArr,6) << endl; char s1[] = "abc"; char s2[] = "ab"; for (size_t i = 0; i < 10; i++) { cout << s1 << " and " << s2 << " max is " << max(s1, s2) << endl; } system("pause"); }