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