Function template  為「通用函式」(Generic function),和一般 function 不同的地方在於,可以為不同type的資料做相同的動作。也就是,將type給參數化,等到呼叫時才決定給的是什麼type。
定義Template
 template <typename T>  
 T GetMin (T a, U b) { 
      return (a<b?  a : b);
 }
 //或者寫成template <class T> T是自己取的參數名稱
 //可傳入兩個不同type的參數,在這個例子裡,這兩種是可以比大小的
使用
 遇到的問題
 function template 只拿回傳 type 當參數時,要明確指定它的 type
 template <class T> T** G(int M, int N) {
     T **ppi;
     /*      */
     return ppi;
 }
 int main(int argc, char *argv[]){
     double **d = G<double>(5,3); <=明確指定double
 }
文章標籤
全站熱搜
創作者介紹
創作者 Y CP 的頭像
Y CP

Y CP的部落格

Y CP 發表在 痞客邦 留言(0) 人氣(26)