- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
#include <tuple>
#include <utility>
#include <array>
namespace detail {
template <typename... Types, std::size_t... Indexes>
auto make_array(const std::tuple<Types...> &t, std::index_sequence<Indexes...>) {
using Tuple = std::tuple<Types...>;
using ValueType = typename std::tuple_element<0, Tuple>::type;
return std::array<ValueType, sizeof...(Types)>{ std::get<Indexes>(t)... };
}
template <typename Value>
constexpr Value fib(std::size_t idx) {
switch (idx) {
case 0: return 1;
case 1: return 1;
default: return fib<Value>(idx - 1) + fib<Value>(idx - 1);
}
}
}
template <class... Args>
auto to_array(const std::tuple<Args...> &t) {
return detail::make_array(t, std::index_sequence_for<Args...>{});
}
template <typename Value, std::size_t size>
class Fibonacci {
public:
constexpr auto as_array() const { return to_array(as_tuple()); }
constexpr operator std::array<Value, size>() const { return as_array(); }
private:
template <std::size_t offset = 0>
constexpr auto as_tuple() const {
return std::tuple_cat(std::tuple{detail::fib<Value>(offset)}, as_tuple<offset + 1>());
}
template <>
constexpr auto as_tuple<size - 1>() const { return std::tuple{detail::fib<Value>(size - 1)}; }
};
int main() {
std::array a = Fibonacci<int, 10>().as_array();
return a[5];
}