为什么显式专业化和部分专业化之间的语法差异

Why the difference in syntax between explicit and partial specialization?

本文关键字:专业化 语法 之间 为什么      更新时间:2023-10-16

示例:

template <typename T, typename U>
struct A {
    void Print() {}
};
template <>
void A<int, float>::Print() {} // Okay                   
template <typename T>
void A<T, char>::Print() {} // Will produce error

问题:

我知道你必须在上面的代码中定义类模板部分专业化才能工作,我也从标准中知道The members of the class template partial specialization are unrelated to the members of the primary template (§ 14.5.5.3)。然而,为什么解释专门化和部分专门化之间的语法差异?

不能部分专门化函数模板,只能完全专门化。

第一个实例利用了这样一个事实,即类模板的成员函数本身就是函数模板,因此限制适用于它们。

当您部分专门化类模板时,您就有了一个全新的类模板,您必须重新定义它。

template <typename T>
void A<T, char>::Print() {} // Will produce error

您是:

  1. 重新定义一个函数(在声明void Print() {}时已经定义了它,您可以看到有{}
  2. 具有与声明不匹配的模板参数列表:template <typename T, typename U> void Print()

事实上,即使您在声明函数时没有定义它,您仍然会出现错误,因为您的声明和定义不匹配,编译器将无法找到原始模板的定义或专用模板的声明。

与结构相关的函数的专用模板函数也必须有一个专用结构

template <typename T, typename U>
struct A {
    void Print() {}
};
template <>
void A<int, float>::Print() {} // Okay                   

template <typename T>
struct A<T,char>
{
    void Print();
};
template <typename T>
void A<T,char>::Print() {}

因为模板函数已在其模板结构中声明。