Skip to content

Instantly share code, notes, and snippets.

@scturtle
Created January 3, 2018 02:53
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 scturtle/a1f4a656833a34ad7dd201d5ff756eca to your computer and use it in GitHub Desktop.
Save scturtle/a1f4a656833a34ad7dd201d5ff756eca to your computer and use it in GitHub Desktop.
fibonacci in tail recursion template
#include <iostream>
template<int N>
struct fibo_result { int val = N; };
template<int ...Ns>
struct fibo_impl;
template<int a, int b, int I, int ...Ns>
struct fibo_impl<a, b, I, I, Ns...>
{
using type = fibo_result<a>;
};
template<int a, int b, int I, int ...Ns>
struct fibo_impl<a, b, I, Ns...>
{
using type = typename fibo_impl<b, a+b, I+1, Ns...>::type;
};
template<int N>
int fibo()
{
return typename fibo_impl<0, 1, 0, N>::type{}.val;
}
int main()
{
std::cout << "fibo(45): " << fibo<45>() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment