Reputation: 9146
What does a template class without arguments mean? For example, let's take a template class who calculate factorial, whose template arguments in N - N!
.
basically, this is the class:
template <int N> class Factorial
{
public:
enum {fact = N * Factorial<N-1>::fact};
};
But, I found that the this class have an "extention class",
template<> class Factorial<1>
{
public:
enum {fact = 1};
};
And here my question is: what does a template without arguments, template<>
mean?
Thanks in advance.
Upvotes: 12
Views: 4569
Reputation: 17708
This
template<> class Factorial<1>
{
public:
enum {fact = 1};
};
is actually a template full specialization or explicit specialization of class template Factorial
. There is also something called template partial specialization. Both are forms of template specialization.
Template specializations are special cases wherein when you instantiate a template with the parameter indicated by the template specialization, that specific template specialization is used, instead of the original template.
In your code, the original Factorial
template class
template <int N> class Factorial
{
public:
enum {fact = N * Factorial<N-1>::fact};
};
is used when you instantiate, for example, the following:
Factorial<3>
Factorial<5>
Factorial<42>
But when you instantiate/use
Factorial<1>
the template specialization Factorial<1>
is used instead. In other words, it is a special case that is used whenever you supply 1
as the template parameter.
One notable example of a template specialization is std::vector<bool>
, though you must be careful whether to use it or not.
Also an example. That show's some minimal usage of template specializations for both class templates and function templates.
Upvotes: 20