C++模板的特化

來源:互聯網
上載者:User

標籤:har   c++類   back   支援   www   char   ble   類型   規則   

C++類模板的三種特化,講得比較全面

By SmartPtr(http://www.cppblog.com/SmartPtr/)

針對一個模板參數的類模板特化的幾種類型, 一是特化為絕對類型(全特化); 二是特化為引用,指標類型(半特化、偏特化);三是特化為另外一個類模板(複雜點的偏特化)。
用一個簡單的例子來說明這三種:

// general versiontemplate<class T>class Compare{public:    static bool IsEqual(const T& lh, const T& rh)    {        return lh == rh;    }};

 

這是一個用於比較的類模板,裡面可以有多種用於比較的函數, 以IsEqual為例。
一、特化為絕對類型
也就是說直接為某個特定類型做特化,這是我們最常見的一種特化方式, 如特化為float, double等

// specialize for floattemplate<>class Compare<float>{public:    static bool IsEqual(const float& lh, const float& rh)    {        return abs(lh - rh) < 10e-3;    }};// specialize for doubletemplate<>class Compare<double>{public:    static bool IsEqual(const double& lh, const double& rh)    {        return abs(lh - rh) < 10e-6;    }};

 

二、特化為引用,指標類型
這種特化我最初是在stl源碼的的iterator_traits特化中發現的, 如下:

template <class _Iterator>struct iterator_traits {  typedef typename _Iterator::iterator_category iterator_category;  typedef typename _Iterator::value_type        value_type;  typedef typename _Iterator::difference_type   difference_type;  typedef typename _Iterator::pointer           pointer;  typedef typename _Iterator::reference         reference;};// specialize for _Tp*template <class _Tp>struct iterator_traits<_Tp*> {  typedef random_access_iterator_tag iterator_category;  typedef _Tp                         value_type;  typedef ptrdiff_t                   difference_type;  typedef _Tp*                        pointer;  typedef _Tp&                        reference;};// specialize for const _Tp*template <class _Tp>struct iterator_traits<const _Tp*> {  typedef random_access_iterator_tag iterator_category;  typedef _Tp                         value_type;  typedef ptrdiff_t                   difference_type;  typedef const _Tp*                  pointer;  typedef const _Tp&                  reference;};

 

當然,除了T*, 我們也可以將T特化為 const T*, T&, const T&等,以下還是以T*為例:

// specialize for T*template<class T>class Compare<T*>{public:    static bool IsEqual(const T* lh, const T* rh)    {        return Compare<T>::IsEqual(*lh, *rh);    }};

 

這種特化其實是就不是一種絕對的特化, 它只是對類型做了某些限定,但仍然保留了其一定的模板性,這種特化給我們提供了極大的方便, 如這裡, 我們就不需要對int*, float*, double*等等類型分別做特化了。

三、特化為另外一個類模板

這其實是第二種方式的擴充,其實也是對類型做了某種限定,而不是絕對化為某個具體類型,如下:

// specialize for vector<T>template<class T>class Compare<vector<T> >{public:    static bool IsEqual(const vector<T>& lh, const vector<T>& rh)    {        if(lh.size() != rh.size()) return false;        else        {            for(int i = 0; i < lh.size(); ++i)            {                if(lh[i] != rh[i]) return false;            }        }        return true;    }};

 

這就把IsEqual的參數限定為一種vector類型, 但具體是vector<int>還是vector<float>, 我們可以不關心, 因為對於這兩種類型,我們的處理方式是一樣的,我們可以把這種方式稱為“半特化”。

當然, 我們可以將其“半特化”為任何我們自訂的模板類類型:

// specialize for any template class typetemplate <class T1> struct SpecializedType{    T1 x1;    T1 x2;};template <class T>class Compare<SpecializedType<T> >{public:    static bool IsEqual(const SpecializedType<T>& lh, const SpecializedType<T>& rh)    {        return Compare<T>::IsEqual(lh.x1 + lh.x2, rh.x1 + rh.x2);    }};

 

這就是三種類型的模板特化, 我們可以這麼使用這個Compare類:

  // int    int i1 = 10;    int i2 = 10;    bool r1 = Compare<int>::IsEqual(i1, i2);    // float    float f1 = 10;    float f2 = 10;    bool r2 = Compare<float>::IsEqual(f1, f2);    // double    double d1 = 10;    double d2 = 10;    bool r3 = Compare<double>::IsEqual(d1, d2);    // pointer    int* p1 = &i1;    int* p2 = &i2;    bool r4 = Compare<int*>::IsEqual(p1, p2);    // vector<T>    vector<int> v1;    v1.push_back(1);    v1.push_back(2);    vector<int> v2;    v2.push_back(1);    v2.push_back(2);    bool r5 = Compare<vector<int> >::IsEqual(v1, v2);    // custom template class     SpecializedType<float> s1 = {10.1f,10.2f};    SpecializedType<float> s2 = {10.3f,10.0f};    bool r6 = Compare<SpecializedType<float> >::IsEqual(s1, s2);

 

C++函數模板的特化

函數模板的特化,函數模板只有全特化,沒有半特化
看下面的例子

main(){    int highest = mymax(5,10);    char c = mymax(‘a’, ’z’);    const char* p1 = “hello”;    const char* p2 = “world”;    const char* p = mymax(p1,p2);}

 


前面兩個mymax都能返回正確的結果.而第三個卻不能,因為,此時mymax直接比較兩個指標p1 和 p2 而不是其指向的內容.
針對這種情況,當mymax函數的參數類型為const char* 時,需要特化。

template <class T>T mymax(const T t1, const T t2){    return t1 < t2 ? t2 : t1;}template <>const char* mymax(const char* t1,const char* t2){    return (strcmp(t1,t2) < 0) ? t2 : t1;}

 


現在mymax(p1,p2)能夠返回正確的結果了

函數模板的偏特化
嚴格的來說,函數模板並不支援偏特化,但由於可以對函數進行重載,所以可以達到類似於類模板偏特化的效果。
template <class T> void f(T); (a)
根據重載規則,對(a)進行重載
template < class T> void f(T*); (b)
如果將(a)稱為基模板,那麼(b)稱為對基模板(a)的重載,而非對(a)的偏特化。

C++的標準委員會仍在對下一個版本中是否允許函數模板的偏特化進行討論。

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.