为什么显式和部分特化之间的语法不同?

时间:2012-01-11 00:57:39

标签: c++ templates template-specialization

示例:

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)的标准中知道。但是,为什么说明专门化和部分专业化之间的语法不同?

2 个答案:

答案 0 :(得分:0)

您不能部分地,仅完全地专门化功能模板。

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

当您对类模板进行部分专门化时,您将拥有一个全新的类模板,您必须重新定义它。

答案 1 :(得分:0)

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

你是:

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

    实际上,即使你在声明它时没有定义函数,你仍然会有一个错误,因为你的声明和定义不匹配,编译器将无法找到原始模板的定义,或者专门模板的声明。

    与结构相关的函数的专用模板函数也必须具有专用结构,此代码有效:

    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() {}
    

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