模板特化,全特化,偏特化,全部特化,部分特化的含義

這幾個名詞真是把人搞混了(是因爲有的著作,甚至名著以訛傳訛),我最近整理了以下,看看大家的意見如何。

模板特化:任何針對模板參數進一步進行條件限制設計的特化版本。《泛型思維》

全特化就是全部特化,即針對所有的模板參數進行特化。《c++ primer》
偏特化就是部分特化,即針對部分模板參數進行特化。《c++ primer》

全特化和偏特化的定義不是很嚴格,所以有的時候不容易讓人理解。

舉例如下:
template<class U,class T>
class C{};
全特化:
template<>
class C<int,char>{};
偏特化:
template<class U>
class C<U,int>{};
大家應該對上面的例子應該沒有什麼異議吧。

再看下面的一個例子:
template<class T,class U>
class C<T*,U*>{};
這屬於全特化還是偏特化呢?一般大部分人都認爲是偏特化,但是按照上面的定義似乎應該是全特化(所有的模板參數都特化了呀)。

我覺得沒有必要在名詞上作口舌之爭,全特化也好,偏特化也好,只要我們掌握它的意義即可。折中的來看,我認爲就可以稱之爲模板特化,畢竟它符合模板特化的含義。

順便說一下:《c++ primer》這本書沒有很好的說明全特化和偏特化的含義,造成很多的歧義,我對這個問題也是迷茫了好久。

規範的原文是這樣的:

The standard term explicit specialization refers to a language feature that we call full specialization instead. It provides an implementation for a template with template parameters that are fully substituted: No template parameters remain. Class templates and function templates can be fully specialized. So can members of class templates that may be defined outside the body of a class definition (i.e., member functions, nested classes, and static data members).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章