用 max 這種 example 應該是最簡單明瞭的...
一般而言,如果你要 "取最大值" 的話,你可以要分幾種情況討論
1. int 取最大 2. float 取最大 3. double 取最大 4. unsigned 取最大.....
所以如果你不用 template 的話,程式碼可能會變這樣...
#include <iostream>
using namespace std;
/////////////////////////////////////////////////
// Max sub function
int Max1(int a, int b)
{
if(a>b) return a;
else return b;
}
float Max2(float a, float b)
{
if(a>b) return a;
else return b;
}
double Max3(double a, double b)
{
if(a>b) return a;
else return b;
}
/////////////////////////////////////////////////
// Main function
int main(int argc, char *argv[])
{
int a=0, b=7;
float c=1.0, d=2.0;
double e=1.35, f=2.78;
cout << "a and b, max is " << Max1(a,b) << endl;
cout << "c and d, max is " << Max2(c,d) << endl;
cout << "e and f, max is " << Max3(e,f) << endl;
return 0;
}
像這種相似,但是卻又一直寫似類東西的,就用 template 的方式取代走會比較方便...
#include <iostream>
using namespace std;
/////////////////////////////////////////////////
// Max sub function
template <class T> T Max(T a, T b)
{
if(a>b) return a;
else return b;
}
/////////////////////////////////////////////////
// Main function
int main(int argc, char *argv[])
{
int a=0, b=7;
float c=1.0, d=2.0;
double e=1.35, f=2.78;
cout << "a and b, max is " << Max(a,b) << endl;
cout << "c and d, max is " << Max(c,d) << endl;
cout << "e and f, max is " << Max(e,f) << endl;
return 0;
}
你可以發現...
template <class T> T Max(T a, T b) {.....}
它裡面的 T 是在你呼叫時,傳入的資料型態是什麼當下才決定的,
當然,你也可以寫得像是這樣..
(先說明,這個例子的用法不好,我只是要告訴你,裡面的不定變數型態可以不只一個)
[code]#include <iostream>
u
[ 瀏覽完整內容請先註冊或登入會員。]