2015-09-25 62 views
4

由兩個GCC-4.9.2和鐺-3.8爲C++ 98或C++ 11編譯時接受,語法明確的模板特

#include <cstdio> 

template <typename T> void f(T) { printf("T\n"); } 
template <> void f<int>(int) { printf("int\n"); } // explicit specialization 
template <> void f<>(double) { printf("double\n"); } // explicit specialization -- 14.7.2(7) 
template <> void f(float) { printf("float\n"); }  // HERE 

int main() { 
    f(1L); // T 
    f(10); // int 
    f(10.0); // double 
    f(10.0F); // float 
} 

我看到以下,在C + +11標準§14.7.2(7)允許在顯式模板專門化中推斷尾隨模板參數,但是我找不到標記爲HERE的terser表單是否被允許。

這些編譯器是符合的還是這個擴展?

+2

這些都不是明確的實例化。他們是明確的*專業*。 –

+0

@ T.C。 ups&謝謝,現在修復。 –

+0

我沒有準確的引用標準,但我記得如果可以推導出類型,至少可以省略函數調用的尖括號。專業化可能也是如此。 – vsoftco

回答

3

C++ 14標準§14.7(3)具有

顯式專業化可以聲明爲函數模板,類模板,類模板或模板構件的一個構件。明確的專業化聲明由模板<>引入。在對類模板,類模板或類成員模板的成員的明確的專門化聲明中,明確專用的類的名稱應該是簡單模板標識。在函數模板或成員函數模板的顯式專門化聲明中,明確專用的函數或成員函數的名稱可以是模板標識。

,然後演示

template<class U> void g(U) { } 
template<> void g(char) { }  //specialize for U == char 
            // U is deduced from the parameter type 

然後我們有§14.7.3(10)

尾隨模板參數可以在模板 - 可以不指定id命名一個顯式的函數模板專門化,前提是它可以從函數參數類型中推導出來。 [實施例:

template<class T> class Array {/.../}; 
template<class T> void sort(Array<T>& v); 

// explicit specialization for sort(Array<int>&) 
// with deduced template-argument of type int 
template<> void sort(Array<int>&); 

末端示例]

+0

這就是有趣的是,C++ 14的§14.7.3(10)似乎是從C++ 11的§14.7.3(8)(嗯,N3376的)我所指的,只不過是那裏的例子讀取'template void sort <>(陣列&);'。 –

+0

@BenjaminBannier你確定嗎? [這](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf)N3376的副本有相同的14.7.3(10)。 – NathanOliver

+0

即使[n1905](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf)從2005年開始。 – NathanOliver