【发布时间】:2011-06-09 06:18:51
【问题描述】:
template<>
class A{
//some class data
};
这种代码我见过很多次了。
上面代码中template<> 有什么用?
在哪些情况下我们需要强制使用它?
【问题讨论】:
-
哦...在使用“模板”发布此内容之前,我尝试用谷歌搜索它,但效果不佳。感谢您提供正确的搜索关键字。但我认为 SO 更好回答它。
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
}
不过,通常情况下,您不应该像 simple overloads are generally considered superior 那样专门化函数:
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 类型的 模板特化。
【讨论】: