For a homework assignement I need to make a Fibonacci struct that uses a template with a single integer input and makes use of template specialisation. Online I found what I needed to make, but I couldn't have made it myself. I feel quite bad, since I don't really understand how it exactly works.
I have trouble with thinking in terms of templates. When I read about the fibonacci algorithm I thought this could be easily done with loops, but that is not allowed for the assignment.
The biggest advantage of a template is (what I've read so far): "a template allows to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type."
I understand what the following part does:
template<>
struct fibonacci<0>
{
static const int value = 0;
};
template<>
struct fibonacci<1>
{
static const int value = 1;
};
When fibonacci<0> or fibonacci<1> is called, the variable value is set to 0 or 1. The main confusion is in the part:
template<int n>
struct fibonacci
{
static const int value = fibonacci<n - 1>::value + fibonacci<n - 2>::value;
};
Questions about individual parts:
template<int n>
Is it correct to assume that this part indicates that only integer values are allowed in the struct?
static const int value
Why is it necessary to put static const
in front of the int value
?
fibonacci<n - 1>::value
Here recursion is used, so I assume that for example n = 3 the fibonacci<2> and fibonacci<1> will be called. For the fibonacci<2> the fibonacci<1> and fibonacci<0> will be called. So for every int n (until overflow) it will apply recursion until the template specialization. I don't really understand the ::value
part. What does happen here?
The whole fibonacci struct:
template<int n>
struct fibonacci
{
static const int value = fibonacci<n - 1>::value + fibonacci<n - 2>::value;
};
template<>
struct fibonacci<0>
{
static const int value = 0;
};
template<>
struct fibonacci<1>
{
static const int value = 1;
};