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.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.
Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With