Partial specialization of c + + class template

Only class templates have partial specialization, not partial specialization function templates.
The so-called partial specialization refers to the provision of another template definition, which is still templated; that is to say, a specialized version designed for further conditional restrictions of the template parameter. This kind of partial specialization can be seen everywhere in STL. For example:

template <class _Iterator>
struct iterator_traits
{
     typedef typename _Iterator::iterator_category
     iterator_category;
     typedef typename _Iterator::value_type        
     value_type;
     typedef typename _Iterator::difference_type  
     difference_type;
     typedef typename _Iterator::pointer
     pointer;
     typedef typename _Iterator::reference
     reference;
};

// specialize for _Tp*
template <class _Tp>
struct iterator_traits<_Tp*> 
{
     typedef random_access_iterator_tag iterator_category;
     typedef _Tp                         value_type;
     typedef ptrdiff_t                   difference_type;
     typedef _Tp*                        pointer;
     typedef _Tp&                        reference;
};

// specialize for const _Tp*
template <class _Tp>
struct iterator_traits<const _Tp*> 
{
     typedef random_access_iterator_tag iterator_category;
     typedef _Tp                         value_type;
     typedef ptrdiff_t                   difference_type;
     typedef const _Tp*                  pointer;
     typedef const _Tp&                  reference;
};

The difference between template specialization and template specialization is that after template specialization, in fact, template itself is not already templated, but partial specialization still has templated. Let's take a practical example:

#include <iostream>
using namespace std;

// General design
template <class T, class T1>
class TestClass
{
public:
     TestClass()
     {
          cout<<"T, T1"<<endl;
     }
};

// Partial specialization design for ordinary pointer
template <class T, class T1>
class TestClass<T*, T1*>
{
public:
     TestClass()
     {
          cout<<"T*, T1*"<<endl;
     }
};

// Partial specialization design for const pointer
template <class T, class T1>
class TestClass<const T*, T1*>
{
public:
     TestClass()
     {
          cout<<"const T*, T1*"<<endl;
     }
};

int main()
{
     TestClass<int, char> obj;
     TestClass<int *, char *> obj1;
     TestClass<const int *, char *> obj2;

     return 0;
}

result:

Call order of specialization and partial specialization:
In the case of template, template specialization and template partial specialization, how to choose when the compiler matches in the compilation phase? From a philosophical point of view, we should first take care of the most special, then the second special, and finally the most common. Compiler choice is also the principle of respect.

Posted on Sun, 03 May 2020 05:11:46 -0400 by Lassie