Can anyone explain to me how does the following output of '5' came about? And how does this particular program works. Because I couldn't for the life of me figure out why it's 5 or how this program works.. Thanks!
Uh oh. That's a template. I'd better create something. What does the Fib<Some_Number> template look like? Looks like this:
1 2 3 4 5 6 7
template <longlong N>
class Fib
{
public:
staticconstlonglong value = Fib<N - 1>::value +
Fib<N - 2>::value;
};
so what does Fib<5> look like? Looks like this:
1 2 3 4 5 6
class Fib
{
public:
staticconstlonglong value = Fib<4>::value +
Fib<3>::value;
};
So now what does your code looks like? Looks kind of like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// THIS IS THE Fib<5> CLASS
class Fib
{
public:
// HERE IS Fib<5>::value
staticconstlonglong value = Fib<4>::value +
Fib<3>::value;
};
int main()
{
// std::cout << 5 << std::endl;
std::cout << Fib<5>::value << std::endl;
}
So what's Fib<5>::value? it's Fib<4>::value + Fib<3>::value
Uh-oh. Fib<4>::value and Fib<3>::value need some template magic. Better do that.
// THIS IS THE Fib<3> CLASS
class Fib
{
public:
// HERE IS Fib<3>::value
staticconstlonglong value = Fib<2>::value +
Fib<1>::value;
};
// THIS IS THE Fib<4> CLASS
class Fib
{
public:
// HERE IS Fib<4>::value
staticconstlonglong value = Fib<3>::value +
Fib<2>::value;
};
// THIS IS THE Fib<5> CLASS
class Fib
{
public:
// HERE IS Fib<5>::value
staticconstlonglong value = Fib<4>::value +
Fib<3>::value;
};
int main()
{
// std::cout << 5 << std::endl;
std::cout << Fib<5>::value << std::endl;
}
So what's Fib<5> value ?
It's Fib<4>::value + Fib<3>::value,
which is ( Fib<3>::value + Fib<2>::value ) + ( Fib<2>::value + Fib<1>::value )
which is ( Fib<2>::value + Fib<1>::value + Fib<2>::value ) + ( Fib<2>::value + Fib<1> )