template<>
class A{
//some class data
};
我已经看过这种代码很多次了。 template<>
在上面的代码中有什么用? 有什么情况下我们需要授权使用它?在C++中带有空尖括号的模板<>的含义是什么?
template<>
class A{
//some class data
};
我已经看过这种代码很多次了。 template<>
在上面的代码中有什么用? 有什么情况下我们需要授权使用它?在C++中带有空尖括号的模板<>的含义是什么?
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<>
class A<foo> {
// some stuff
};
...这将是Foo类型一个模板特。
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
// ...
}
这看起来很奇怪,因为它是一个更强大的功能,这就是所谓的特殊情况“部分的专业化。”
明确的(不是“全部”)专业化并不是部分专业化的特例。显式特化定义了一个由模板标识符标识的类;部分专业化定义了通过主模板访问的新模板。 – Potatoswatter 2011-06-09 17:54:01
我更喜欢“total”这个词,因为它被“partial”(这是一种东西)所反对,而“explicit”则被“implicit”(这不是一种东西)所反对。我知道这不是标准术语。 语法上,显式特化是部分特化的一种特殊情况,即使以最标准的方式查看二者,也会区分类和类模板。 – 2011-06-09 18:27:05
哦...我试图谷歌它之前发布与“模板<>”,这不会产生我好结果。感谢正确的搜索关键词。但我认为SO有更好的答案,它。 – Vijay 2011-06-09 06:28:38