問題描述
template<>
class A{
//some class data
};
這種代碼我見過很多次了.上面代碼中template<>
的作用是什么?在哪些情況下我們需要強制使用它?
I have seen this kind of code many times.
what is the use of template<>
in the above code?
And what are the cases where we need mandate the use of it?
推薦答案
template<>
告訴編譯器遵循模板特化,特別是完全特化.通常,class A
應該是這樣的:
template<>
tells the compiler that a template specialization follows, specifically a full specialization. Normally, class A
would have to look something like this:
template<class T>
class A{
// general implementation
};
template<>
class A<int>{
// special implementation for ints
};
現在,每當使用 A
時,都會使用專用版本.你也可以用它來專門化函數:
Now, whenever A<int>
is used, the specialized version is used. You can also use it to specialize functions:
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
}
通常情況下,你不應該專門化函數,因為簡單的重載通常被認為是優越的:
Normally though, you shouldn't specialize functions, as 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
、B
等).
Works the same way as a full specialization, just that the specialized version is used whenever the second template parameter is an int
(e.g., B<bool,int>
, B<YourType,int>
, etc).
這篇關于模板是什么意思?在 C++ 中使用空尖括號?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!