C++拾遺--函數模板,拾遺--函數模板

來源:互聯網
上載者:User

C++拾遺--函數模板,拾遺--函數模板

                        C++拾遺--函數模板

前言

    泛型的核心思想是資料與演算法分離。函數模板是泛型程式設計的基礎。

函數模板

函數模板以 template<arg_list> 開頭,arg_list是泛型參數的列表。

1.模板的泛型參數個數確定執行個體一

下面是一個加法函數模板,在執行個體化時,我們傳入普通的資料類型。

#include <iostream>using namespace std;template<typename T1, typename T2>auto add(T1 t1, T2 t2)->decltype(t1 + t2){return t1 + t2;}int main(){cout << add(12.3, 12) << endl;cout << add(12, 12.3) << endl;cin.get();return 0;}
運行


執行個體二

我們也可以傳入函數類型。

#include <iostream>using namespace std;template<typename T, typename F>void exec(const T &t, F f){f(t);}int main(){exec("calc", system);cin.get();return 0;}
運行 system("calc"); 開啟計算機



2.模板的泛型參數個數不確定

#include <iostream>#include <cstdarg>using namespace std;//這個空參的函數用於遞迴終止void show(){}//參數個數可變,參數類型也多樣template<typename T, typename...Args>    //typename...Args是可變類型列表void show(T t, Args...args){cout << t << ends;show(args...);}int main(){show(1, 2, 3, 4); cout << endl;show('a', 'b', 'c', 'd');cin.get();return 0;}
運行



下面利用函數模板來簡單的模仿下printf()函數

#include <iostream>#include <cstdarg>using namespace std;void PRINTF(const char *format){cout << format;}template<typename T, typename...Args>void PRINTF(const char *format, T t, Args...args){if (!format || *format == '\0')return;if (*format == '%')    //處理格式提示符{format++;char c = *format;if (c == 'd' || c == 'f' || c == 'c' || c == 'g')   //我們暫且只處理這幾種,其它的同理{cout << t;format++;PRINTF(format, args...);}else if (c == '%'){cout << '%';format++;PRINTF(format, t, args...);}else{cout << *format;format++;PRINTF(format, t, args...);}}else{cout << *format;PRINTF(++format, t, args...);}}int main(){PRINTF("%asdljl%5234la;jdfl;\n");PRINTF("%d alsd, %fasdf..%g..%c\n", 12, 3.4, 5.897, 'a');cin.get();return 0;}
運行



利用函數模板簡易類比printf()代碼下載




所有內容的目錄

  • CCPP Blog 目錄




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.