C++程式設計方法4:模板特化

來源:互聯網
上載者:User

標籤:iostream   type   編譯   具體類   code   列表   names   har   new   

模板參數的具體化/特殊化

有時,有些類型不適用,則需要對模板進行特殊化處理,這稱為“模板特化”

對函數模板,如果有多個模板參數,則特化時必須提供所有參數的特例類型,不能部分特化;

 

如:

  char *sum(char *,char *);

在函數名後用<>括弧括起具體類型

template<> char* sum<char*>(char* a,char* b){...}

由編譯器推匯出具體的類型,函數名為普通形式:

template<> char *sum(char* a ,char *b){}

 

對於類模板,允許部分特化,即部分限制模板的通用性,如:
//通用模板類

template<class T1,class T2>class A{...};

//部分特化的模板類:第二個型別參數指定為int

template<class T1>class A<T1,int>{...};

若指定所有的類型,則<>內將為空白

template<>class A<int,int>{...};

#include <iostream>using namespace std;template<typename T> T sum(T a, T b){    return a + b;}//因為是特化,類型已知,所以模板參數列表為空白;template<>char* sum(char* a, char* b){    char* p = new char[strlen(a) + strlen(b) + 1];    strcpy(p, a);    strcat(p, b);    return p;}int main(){    cout << sum(3, 4) << " " << sum(5.1, 13.8) << endl;    //調用普通的函數模板    char *str1 = "hello,", *str2 = "world";    //調用特例化的函數模板    cout << sum(str1, str2) << endl;    return 0;}

類模板的特化執行個體:

#include <iostream>using namespace std;template<typename T>class Sum{    T a, b;public:    Sum(T op1, T op2) :a(op1), b(op2) {}    T DoIt() { return a + b;}};//替換T,特例化template<>class Sum<char*>{    char *str1, *str2;public:    Sum(char *s1, char *s2) :str1(s1), str2(s2) {}    char *DoIt()    {        char *tmp = new char[strlen(str1) + strlen(str2) + 1];        strcpy(tmp, str1);        strcat(tmp, str2);        return tmp;    }};int main(){    Sum<int> obj1(3, 4);    cout << obj1.DoIt() << endl;    char *s1 = "hello", *s2 = "THU";    Sum<char *> obj2(s1, s2);    cout << obj2.DoIt() << endl;    return 0;}

 

C++程式設計方法4:模板特化

聯繫我們

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