C++中有類模板和函數模板,它們的定義如下所示:
類模板:
template<class T1,class T2>
class C
{
//...
};
函數模板:
template<class T1,class T2>
void func(T1 p1,T2 p2)
{
//...
};
特化包括全特化和偏特化,全特化也叫簡稱特化,所以說特化的時候意思就是全特化。
特化就是對所有的模板參數指定一個特定的類型,偏特化就是對部分模板參數指定特定的類型。
類模板的特化:
template<class T1,class T2> //這裡是類模板
class C
{
//...
};
template<> //這裡是對C的特化
class C<int,int>
{
//...
};
從語法上看,全特化的時候,template後面尖括號裡面的模板參數列表必須是空的,表示該特化版本沒有模板參數,全部都被特化了。
類模板的偏特化:
template<class T1,class T2> //這裡是類模板
class C
{
//...
};
template <class T1> //這裡是對C的偏特化
class C<T1,int>
{
//...
};
從語法上看,偏特化的時候,template後面的尖括號裡面的模板參數列表必須列出未特化的模板參數。同時在C後面要全部列出模板參數,同時指定特化的類型,比如指定int為T2的特化類型。
函數模板的特化:
template<class T1,class T2> //這裡是函數模板
void func(T1 p1,T2 p2)
{
//...
};
template <> //這裡是對函數模板的特化
void func(int p1,int p2)
{
//...
};
函數模板的偏特化:
函數模板不能進行偏特化!!!!!
//--------------------------------------------------------
STL中iterator_traits的偏特化
STL中的iterator_traits用來返回iterator中定義好的五種類型。其具體實現應該是:
template<class Iterator>
struct iterator_traits
{
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
typedef typename Iterator::iterator_category iterator_category;
};
因為指針也是一種iterator,如果將指針作為模板參數,上面的定義就會失效。因此上面的模板必須對指針進行特化。特化的代碼如下所示:
template<class T>
struct iterator_traits<T*>
{
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef random_access_iterator_tag iterator_category;
};
而且還需要對 const T* 進行特化,否則 value_type 就成了 const T 類型,這通常不是我們想要的.
template<class T>
struct iterator_traits<const T*>
{
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef const T* pointer;
typedef const T& reference;
typedef random_access_iterator_tag iterator_category;
};
內容主要來自: http://blog.csdn.net/timewalker08/article/details/7195698