there seems to be nothing much happening in the c++ forum today. so here is something to chew on for programmers who are relatively new to templates: c++ can also be used as a metalanguage.
#include <iostream>
using namespace std ;
// compile-time computation of fibonacci numbers
template < int N > struct fibonacci
{
char error_negetive_N[ N + 1 ] ; // c++0x => use static_assert
enum { value = fibonacci<N-1>::value + fibonacci<N-2>::value } ;
char error_integer_overflow[ value ] ; // c++0x => use static_assert
};
template<> struct fibonacci<0> { enum { value = 0 } ; } ;
template<> struct fibonacci<1> { enum { value = 1 } ; } ;
// compile-time if statement
template<bool> struct _if { static inline void new_line() {} };
template<> struct _if<true>
{ static inline void new_line() { cout << '\n' ; } };
// compile-time for loop
template< int N, int MAX, size_t N_PER_LINE > struct _for
{
static inline void print_fibonacci_number()
{
cout << fibonacci<N>::value << '\t' ;
_if< N%N_PER_LINE == (N_PER_LINE-1) >::new_line() ;
_for< N+1, MAX, N_PER_LINE >::print_fibonacci_number() ;
}
};
template< int MAX, size_t N_PER_LINE > struct _for<MAX,MAX,N_PER_LINE>
{
static inline void print_fibonacci_number()
{ _if< MAX%N_PER_LINE >::new_line() ; }
} ;
int main()
{
enum { FROM = 0, TILL = 32, LINE_SZ = 8 } ;
_for< FROM, TILL, LINE_SZ >::print_fibonacci_number() ;
}
// to see generated assembly along with c++ source code (gcc):
// c++ -c -g -Wa,-a,-ad -Wall -std=c++98 -O3 fib.cpp > fib.asm
/**
>c++ -Wall -std=c++98 fib.cpp && ./a.out
0 1 1 2 3 5 8 13
21 34 55 89 144 233 377 610
987 1597 2584 4181 6765 10946 17711 28657
46368 75025 121393 196418 317811 514229 832040 1346269
*/
// for a discussion/elaboration of the technique, see
// http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html