简体   繁体   中英

Why the difference in syntax between explicit and partial specialization?

Example:

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

Question:

I know that you have to define the class template partial specialization in the above code for it to work and I also know from the standard that The members of the class template partial specialization are unrelated to the members of the primary template (§ 14.5.5.3) . However, why the difference in syntax between a explication specialization and a partial specialization?

You cannot specialize function templates partially, only fully.

The first instance makes use of the fact that member functions of class templates are themselves function templates, and thus the restriction applies to them.

When you partially-specialize the class template, you have an entirely new class template, which you have to define anew.

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

You are:

  1. re-defining a function (it has already been defined when declared void Print() {} , you see there are {} .
  2. with a template argument list that doesn't match the declaration: template <typename T, typename U> void Print()

In fact, even if you haven't defined the function when declared it, you will still have an error since your declaration and definition do not match, the compiler will not be able to find a definition for the original template, or a declaration for the specialized template.

A specialized template function for a function that is related to a struct must have a specialized struct as well, This code works:

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

Because template function has been declared in it's template struct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM