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>
等)。
关于c++ - C++中带有空尖括号的模板<>是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288812/