diff options
author | timstr | 2022-10-31 01:06:26 +0000 |
---|---|---|
committer | timstr | 2022-10-31 01:06:26 +0000 |
commit | 2ceccb698b01ad56ca75f2b99235bb23806a000e (patch) | |
tree | 914e724f6af8877ec7b77b6e59796bcd1c8d7497 | |
parent | b843442b2b69125a7b184c37dbc0bb9d8da7c170 (diff) |
Fibonacci in C++ using compile-time template meta-programming and inheritance-based templated loop unrolling
-rw-r--r-- | entries/timstr/fib.cpp | 35 |
1 files changed, 35 insertions, 0 deletions
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 <iostream> +#include <cstdint> + +template<std::size_t N> +struct fib { + static constexpr std::size_t value = fib<N - 1>::value + fib<N - 2>::value; +}; + +template<> +struct fib<0> { + static constexpr std::size_t value = 1; +}; + +template<> +struct fib<1> { + static constexpr std::size_t value = 1; +}; + +template<std::size_t N> +constexpr std::size_t fib_v = fib<N>::value; + +template<std::size_t N> +struct print_fib : print_fib<N - 1> { + print_fib() noexcept { + std::cout << fib_v<N - 1> << '\n'; + } +}; + +template<> +struct print_fib<0> {}; + +int main() { + print_fib<32>{}; + return 0; +}
\ No newline at end of file |