Something went wrong. Try again.
A Tour of C++ for experienced programmers, as if C++26 is the only version that ever existed.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#include <coroutine>#include <exception>
#include <iostream>#include <cstdint>#include <optional>
// Minimal generator for uint64_t values.template <typename T>struct simple_generator { struct promise_type { std::optional<T> current; auto get_return_object() { return simple_generator{handle_type::from_promise(*this)}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } std::suspend_always yield_value(T value) noexcept { current = std::move(value); return {}; } void return_void() noexcept {} void unhandled_exception() { std::abort(); } }; using handle_type = std::coroutine_handle<promise_type>; handle_type coro; explicit simple_generator(handle_type h) : coro(h) {} simple_generator(const simple_generator&) = delete; simple_generator& operator=(const simple_generator&) = delete; simple_generator(simple_generator&& other) noexcept : coro(other.coro) { other.coro = nullptr; } simple_generator& operator=(simple_generator&& other) noexcept { if (this != &other) { if (coro) coro.destroy(); coro = other.coro; other.coro = nullptr; } return *this; } ~simple_generator() { if (coro) coro.destroy(); } struct iterator { handle_type coro; bool done; iterator(handle_type h, bool d) : coro(h), done(d) {} iterator& operator++() { coro.resume(); done = coro.done(); return *this; } const T& operator*() const { if (!coro.promise().current.has_value()) std::abort(); return coro.promise().current.value(); } bool operator==(std::default_sentinel_t) const { return done; } }; iterator begin() { coro.resume(); return iterator{coro, coro.done()}; } std::default_sentinel_t end() const { return {}; }};
simple_generator<std::uint64_t> fibonacci() { std::uint64_t a = 0, b = 1; while (true) { co_yield a; auto next = a + b; a = b; b = next; }}
int main() { std::size_t N = 11; std::size_t i = 0; for (auto v : fibonacci()) { std::cout << v << (i + 1 == N ? '\n' : ' '); if (++i >= N) break; } return 0;}