2015-09-25 36 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