是吗
template <typename T>
void foo(T) {}
template <>
void foo(int) {}
显式特化或函数重载,以及对于显式初始化编译器想看下面的代码吗?
template <typename T>
void foo(T) {}
template <>
void foo<int>(int) {}
我认为该标准接受这两种:
ISO/IEC 14882:2011
14.7.3 Explicit specialization [temp.expl.spec] 1 ... can be declared by a declaration introduced by template<>; that is: explicit-specialization: template < > declaration
最佳答案
两者皆可。在特化
template <>
void foo(int) {}
编译器从函数参数中推断出模板参数T = int
。从 14.7.3p10 开始:
A trailing template-argument can be left unspecified in the template-id naming an explicit function template specialization provided it can be deduced from the function argument type.
给出的示例涉及类模板的推导,但它同样适用于直接使用的类型的推导:
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>&);
关于c++ - 显式特化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13535223/