What does a template class with no arguments mean, `template <>`?

What does a template class without arguments mean? For example, let's take a template class that computes factorial, whose template arguments are N - N! .

this is basically a class:

 template <int N> class Factorial { public: enum {fact = N * Factorial<N-1>::fact}; }; 

But I found that this class has an "extension class",

 template<> class Factorial<1> { public: enum {fact = 1}; }; 

And here is my question: what does a template without arguments mean, template<> means?

Thanks in advance.

+4
source share
1 answer

it

 template<> class Factorial<1> { public: enum {fact = 1}; }; 

it is actually a template for the full specialization or explicit specialization of a template of the Factorial class. There is also something called private specialization. Both are forms of specialization pattern .

Template specialization is a special case when when creating a template with the parameter specified by the template specialization, a special template specification is used instead of the original template.

In your code, the source class Factorial

 template <int N> class Factorial { public: enum {fact = N * Factorial<N-1>::fact}; }; 

used when you create an instance, for example, the following:

  • Factorial<3>
  • Factorial<5>
  • Factorial<42>

But when you create / use

 Factorial<1> 

instead, the Factorial<1> template specification is used. In other words, this is a special case that is used when you add 1 as a template parameter.

One notable example of template specialization is std::vector<bool> , although you should be careful to use it or not .

Also an example . This shows the minimal use of specialized templates for class templates and function templates.

+10
source

Source: https://habr.com/ru/post/1494625/


All Articles