1. 简介
完全特化(full specialization)也叫显式特化(explict specialization). 它允许为给定的模板实参自定义模板代码.
2. 语法
template <> declaration
必须实例化所有的模板形参.
如,
#include
template
struct IsVoid
{
static constexpr bool value = false;
};
template <>
struct IsVoid
{
static constexpr bool value = true;
};
int main()
{
std::cout << std::boolalpha << IsVoid::value << '\n'; // false
std::cout << std::boolalpha << IsVoid::value << '\n'; // true
}
3. 什么时候不需要加上 template <>?
(1)如果你正在显式特化一个模板,则应该加上 template <>
.
template class Array { /*...*/ };
// primary template
template void sort(Array& v);
// specialization for T = int
template<> void sort(Array&);
template
struct A {
struct B {}
template struct C { };
};
template <>
struct A {
void f(int);
};
(2)如果你正在为一个已显式特化的类模板定义成员,则不需要加上 template <>
.
void A::f(int) {}
此时 A
已是一个具体的类,不再是模板,没有模板形参,不再是可以被特化的实体了.
(3)如果模板 A 之前没有被显式特化过,而你正在为 Atemplate <>
.
template<>
struct A::B {
void f();
};
(4)如果模板 A 之前没有被显式特化过,但已为 Atemplate <>
.
void A::B::f() {}
A
已是具体的类型,不可特化.
(5)如果模板 A 之前没有被显式特化过,但已为 Atemplate <>
.
template<>
template
struct A::C {
void f();
};
template<>
template
void A::C::f() { /* ... */ }
(6)如果类模板的成员也是一个模板,也可以将其显式特化.
template
struct A {
template void g1(T, U);
};
template<>
template<>
void A::g1(int, char);
template<>
template<>
void A::g1(int, char) {}
(7)如果类模板 A 已显式特化,其成员 C 是一个类模板,则在显式特化 C 时,不需要加上 template <>
.
template
struct A {
struct B {}
template struct C { };
};
template <>
struct A {
template struct C { };
};
template <>
struct A::C {
void f();
};
void A::C::f() {}