Fibonacci numbers (C Plus Plus templates)

From LiteratePrograms

Jump to: navigation, search
Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

1 \\ \end{cases} ."/>

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


Implementation

The Fibonacci numbers implemented with a template in C++:

<<fib.cpp>>=
includes
fib
main
<<includes>>=
#include<iostream>

Template

<<fib>>=
template<unsigned int n> struct fib
{
	static const unsigned int result=fib<n-1>::result+fib<n-2>::result;
};
template<> struct fib<1>
{
	static const unsigned int result=1;
};
template<> struct fib<0>
{
	static const unsigned int result=0;
};

Test driver

The Fibonacci numbers will be calculated at compile-time, when the fib template class is instantiated.

<<main>>=
int main()
{
	std::cout<<"fib<1>="<<fib<1>::result<<'\n';
	std::cout<<"fib<2>="<<fib<2>::result<<'\n';
	std::cout<<"fib<3>="<<fib<3>::result<<'\n';
	std::cout<<"fib<4>="<<fib<4>::result<<'\n';
	std::cout<<"fib<5>="<<fib<5>::result<<'\n';
	std::cout<<"fib<40>="<<fib<40>::result<<'\n';
	std::cout<<"fib<41>="<<fib<41>::result<<'\n';
	std::cout<<"fib<42>="<<fib<42>::result<<'\n';
	std::cout<<"fib<43>="<<fib<43>::result<<'\n';
	return 0;
}

See Fibonacci numbers (C) for runtime calculation of Fibonacci numbers.

Download code
Views