Skip to content

Instantly share code, notes, and snippets.

@scturtle scturtle/fibo.cc
Created Jan 3, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.