From 2ceccb698b01ad56ca75f2b99235bb23806a000e Mon Sep 17 00:00:00 2001 From: timstr Date: Sun, 30 Oct 2022 18:06:26 -0700 Subject: Fibonacci in C++ using compile-time template meta-programming and inheritance-based templated loop unrolling --- entries/timstr/fib.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 entries/timstr/fib.cpp diff --git a/entries/timstr/fib.cpp b/entries/timstr/fib.cpp new file mode 100644 index 0000000..08e5802 --- /dev/null +++ b/entries/timstr/fib.cpp @@ -0,0 +1,35 @@ +#include +#include + +template +struct fib { + static constexpr std::size_t value = fib::value + fib::value; +}; + +template<> +struct fib<0> { + static constexpr std::size_t value = 1; +}; + +template<> +struct fib<1> { + static constexpr std::size_t value = 1; +}; + +template +constexpr std::size_t fib_v = fib::value; + +template +struct print_fib : print_fib { + print_fib() noexcept { + std::cout << fib_v << '\n'; + } +}; + +template<> +struct print_fib<0> {}; + +int main() { + print_fib<32>{}; + return 0; +} \ No newline at end of file -- cgit v1.2.3-70-g09d2