Skip to content

Instantly share code, notes, and snippets.

@kasajian
Created May 20, 2014 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasajian/1e8db34b6e227492b239 to your computer and use it in GitHub Desktop.
Save kasajian/1e8db34b6e227492b239 to your computer and use it in GitHub Desktop.
Calculate Fibonacci at compile time in C++
#include <stdio.h>

// The following code prints out the first five elements of the
// fibonacci series without calculating the values at runtime.

template <int param>
struct CFibonacci
{
    static const value;
};

template <int param>
const CFibonacci<param>::value = 
CFibonacci<param - 2>::value + CFibonacci<param - 1>::value;

const CFibonacci<0>::value = 0;
const CFibonacci<1>::value = 1;


void main( void )
{
    printf( "%d\n", CFibonacci<1>::value );
    printf( "%d\n", CFibonacci<2>::value );
    printf( "%d\n", CFibonacci<3>::value );
    printf( "%d\n", CFibonacci<4>::value );
    printf( "%d\n", CFibonacci<5>::value );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment