函數樣板
省去因為型態問題
而再次宣告的麻煩
讓我們學習如何撰寫
函數樣板
是泛型函數的描述
也就是說
以型態定義函數
因為樣板是以泛型型態
而非特定型態來進行程式設計
所以稱為泛型程式設計
因為型態以參數表示
樣板的特性又稱為參數化型態
如果我們預先寫出了交換int型態的函數:
[code language=”cpp”]
#include <iostream>
using namespace std;
void change(int &,int &);
int main(){
int s1=5,s2=10;
cout << "s1=" << s1 << " s2=" << s2 << endl;
change(s1,s2);
cout << "s1=" << s1 << " s2=" << s2 << endl;
}
void change(int &a,int &b){
int temp;
temp=a;
a=b;
b=temp;
}
[/code]
如果要改成交換double型態
手動處理的話
就必須要一個一個將int改成double
會是一件很麻煩的事情
而且很容易出錯
那將來如果交換float型態、char型態值呢?
因此出現了函數樣板
方便程式設計者更有效率的撰寫
宣告
template <typename 自訂型態名稱>
void 函數名稱 (自訂型態名稱 參數1,自訂型態名稱 參數2…){
………
}
Ex:
更改上面範例變成函數樣板
[code language=”cpp”]
#include <iostream>
using namespace std;
template <typename mytype> //函數樣板宣告
void change(mytype &a,mytype &b){ //函數原型宣告、定義
mytype temp;
temp=a;
a=b;
b=temp;
}
int main(){
int s1=5,s2=10;
cout << "s1=" << s1 << " s2=" << s2 << endl;
change(s1,s2); //交換int型態變數
cout << "s1=" << s1 << " s2=" << s2 << endl;
double p1=5.4,p2=10.67;
cout << "p1=" << p1 << " p2=" << p2 << endl;
change(p1,p2); ////交換double型態變數
cout << "p1=" << p1 << " p2=" << p2 <<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>< endl;
}
[/code]