显式模板专门化的语法

Syntax for explicit template specializations

本文关键字:语法 专门化      更新时间:2023-10-16

当编译为c++ 98或c++ 11时,gcc-4.9.2和clang-3.8都接受以下内容,

#include <cstdio>
template <typename T> void f(T) { printf("Tn"); }
template <> void f<int>(int) { printf("intn"); }    // explicit specialization
template <> void f<>(double) { printf("doublen"); } // explicit specialization -- 14.7.2(7)
template <> void f(float) { printf("floatn"); }     // HERE
int main() {
  f(1L);    // T
  f(10);    // int
  f(10.0);  // double
  f(10.0F); // float
}

我看到在c++ 11标准§14.7.2(7)中允许在显式模板特化中推导末尾的模板参数,但我找不到标记为HERE的更简洁的形式是否或如何被允许。

这些编译器是一致的还是这是一些扩展?

14 c++标准§14.7 (3)

可以为函数模板、类模板、类模板的成员或成员模板声明显式特化。一个显式特化声明是由template<>引入的。在类模板、类模板成员或类成员模板的显式特化声明中,被显式特化的类的名称应该是simple-template-id。在函数模板或成员函数模板的显式特化声明中,显式特化的函数或成员函数的名称可以是template-id。

然后演示

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)

如果可以从函数实参类型推断出,则可以在指定显式函数模板专门化的template-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>&);

-end example]