c++多態實現之三 -- 模板

來源:互聯網
上載者:User

標籤:

模板是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++多態實現之三 -- 模板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.