template<>
class A{
//some class data
};
我经常看到这类代码。上述代码中的template<>
有什么用?在哪些情况下需要强制使用它?template<>
告诉编译器后面是一个模板特化,具体来说是完全特化。通常,class A
应该像这样:
template<class T>
class A{
// general implementation
};
template<>
class A<int>{
// special implementation for ints
};
A<int>
时,都会使用专门化的版本。您还可以使用它来专门化函数:template<class T>
void foo(T t){
// general
}
template<>
void foo<int>(int i){
// for ints
}
// doesn't actually need the <int>
// as the specialization can be deduced from the parameter type
template<>
void foo(int i){
// also valid
}
void foo(int i){
// better
}
现在,为了更加完整,以下是部分特化:
template<class T1, class T2>
class B{
};
template<class T1>
class B<T1, int>{
};
这个模板和完整的特化模板一样,只是当第二个模板参数是int
时,就会使用特殊版本(例如:B<bool,int>
、B<YourType,int>
等)。
template<>
引入模板的完全特化。你提供的例子本身实际上不是有效的;在变得有用之前,你需要一个更详细的场景:
template <typename T>
class A
{
// body for the general case
};
template <>
class A<bool>
{
// body that only applies for T = bool
};
int main()
{
// ...
A<int> ai; // uses the first class definition
A<bool> ab; // uses the second class definition
// ...
}
这看起来很奇怪,因为它是更强大的“部分特化”功能的一个特殊案例。
template<>
class A<foo> {
// some stuff
};
...这将是类型foo的模板特化。