Created
December 20, 2017 22:34
-
-
Save chiroptical/23fb5d19f382cb110219562a62b4e669 to your computer and use it in GitHub Desktop.
Potentially Tail Call
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
template <int n, int prev, int next, bool isPositive> | |
struct fib_impl { | |
static constexpr int val = fib_impl<n - 1, next, prev + next, isPositive>::val; | |
}; | |
template <int prev, int next> | |
struct fib_impl<0, prev, next, true> { | |
static constexpr int val = prev; | |
}; | |
template <int n, int prev, int next> | |
struct fib_impl<n, prev, next, false> { | |
static constexpr int val = -1; | |
}; | |
template <int n> | |
struct fib { | |
static_assert(n >= 0, "Error: fib can't be called with negative numbers!"); | |
static constexpr int val = fib_impl<n, 0, 1, (n >= 0)>::val; | |
}; | |
int main() { | |
static_assert(fib<10>::val == 55); | |
static_assert(fib<0>::val == 0); | |
static_assert(fib<1>::val == 1); | |
// static_assert(fib<-1>::val); // this will fail :) | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment