標籤:
模板是C++支援參數化多態的工具,使用模板可以使使用者為類或者函式宣告一種一般模式,使得類中的某些資料成員或者成員函數的參數、傳回值取得任意類型。
模板是一種對類型進行參數化的工具;
通常有兩種形式:函數模板和類模板;
函數模板針對僅參數類型不同的函數;
類模板針對僅資料成員和成員函數類型不同的類。
使用模板的目的就是能夠讓程式員編寫與類型無關的代碼。比如編寫了一個交換兩個整型int 類型的swap函數,這個函數就只能實現int 型,對double,字元這些類型無法實現,要實現這些類型的交換就要重新編寫另一個swap函數。使用模板的目的就是要讓這程式的實現與類型無關,比如一個swap模板函數,即可以實現int 型,又可以實現double型的交換。模板可以應用於函數和類。下面分別介紹。
注意:模板的聲明或定義只能在全域,命名空間或類範圍內進行。即不能在局部範圍,函數內進行,比如不能在main函數中聲明或定義一個模板。
具體的模板使用方法請參考專門將模板的書籍。
這裡舉個模板使用例子:實現封裝c++11的線程。
#include <thread>#include <iostream>#include <list>using namespace std;class thead_group{private: thread_group(const thread_group&){} //禁用拷貝構造和賦值 thread_group& operator=(const thread_group&){} pubcli: template<typename... T>//可變參數列表模板 void thread_create(T... func) { thread* p_thread = new thread(func...); vct_thread.push(p_thread); } void thread_join() { for(const auto &thrd : vct_threads) { thrd->join(); } }private: list<thread*> vct_threads;}void func1(){ cout << "this is func1" << endl;} void func2(int a){ cout << "this is fun2, param : " << a << endl; }int main(int argc, char** argv){ thread_group thrd; thrd.create_thread(func1); thrd.create_thread(func2, 10); thrd.thread_join(); return 0;}
輸出結果:this is func1 this is func2, param : 10
c++多態實現之三 -- 模板