C++模板—部分特化

【C++模板—部分特化】1. 简介
部分特化(partial specialization)允许为给定类别的模板实参自定义类模板和变量模板.
2. 语法

template class ClassName declaration

其中,argument-list 可以包含具体的类型(对应类型参数)、具体的值(对应非类型参数),也可以包含在 中指定的模板形参.
如,
// primary template template class A {}; // #1: partial specialization where T2 is a pointer to T1 template class A {}; // #2: partial specialization where T1 is a pointer template class A {}; // #3: partial specialization where T1 is int, I is 5, and T2 is a pointer template class A {}; // #4: partial specialization where T2 is a pointer template class A {};

具体例子:移除引用
#include template struct RemoveReference { using type = T; }; template struct RemoveReference { using type = T; }; template struct RemoveReference { using type = T; }; int main() { std::cout << std::boolalpha << std::is_reference::value << '\n'; std::cout << std::boolalpha << std::is_reference::value << '\n'; std::cout << "---------------------\n"; std::cout << std::boolalpha << std::is_reference::type>::value << '\n'; std::cout << std::boolalpha << std::is_reference::type>::value << '\n'; std::cout << std::boolalpha << std::is_reference::type>::value << '\n'; }

true true --------------------- false false false

3. 部分特化的成员
(1)成员的模板形参列表、模板实参列表必须和部分特化的形参列表、实参列表一致.
// primary template template struct A { void f(); }; // primary template member definition template void A::f() { }// partial specialization template struct A { void f(); void g(); void h(); }; // member of partial specialization template void A::g() { }

(2)部分特化的成员也可以进一步显式特化.
// explicit (full) specialization of a member of partial specialization template<> void A::h() {}

(3)外围类模板的特化要优先于内层类模板的特化.
template struct A { // primary member template template struct B {}; // partial specialization of member template template struct B {}; }; // full specialization of primary member template (will ignore the partial) template<> template struct A::B {}; A::B abcip; // uses partial specialization T2=int A::B absip; // uses full specialization of the primary (ignores partial) A::B abci; // uses primary

    推荐阅读