這幾個(gè)名詞真是把人搞混了(是因?yàn)橛械闹鳎踔撩杂瀭饔灒易罱砹艘韵拢纯创蠹业囊庖娙绾巍?br>
模板特化:任何針對(duì)模板參數(shù)進(jìn)一步進(jìn)行條件限制設(shè)計(jì)的特化版本。《泛型思維》
全特化就是全部特化,即針對(duì)所有的模板參數(shù)進(jìn)行特化。《c++ primer》
偏特化就是部分特化,即針對(duì)部分模板參數(shù)進(jìn)行特化。《c++ primer》
全特化和偏特化的定義不是很嚴(yán)格,所以有的時(shí)候不容易讓人理解。
舉例如下:
template<class U,class T>
class C{};
全特化:
template<>
class C<int,char>{};
偏特化:
template<class U>
class C<U,int>{};
大家應(yīng)該對(duì)上面的例子應(yīng)該沒有什么異議吧。
再看下面的一個(gè)例子:
template<class T,class U>
class C<T*,U*>{};
這屬于全特化還是偏特化呢?一般大部分人都認(rèn)為是偏特化,但是按照上面的定義似乎應(yīng)該是全特化(所有的模板參數(shù)都特化了呀)。
我覺得沒有必要在名詞上作口舌之爭(zhēng),全特化也好,偏特化也好,只要我們掌握它的意義即可。折中的來看,我認(rèn)為就可以稱之為模板特化,畢竟它符合模板特化的含義。
順便說一下:《c++ primer》這本書沒有很好的說明全特化和偏特化的含義,造成很多的歧義,我對(duì)這個(gè)問題也是迷茫了好久。
規(guī)范的原文是這樣的:
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).