Created
January 3, 2018 02:53
-
-
Save scturtle/a1f4a656833a34ad7dd201d5ff756eca to your computer and use it in GitHub Desktop.
fibonacci in tail recursion template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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