How do I use coroutines in C++20?

Learn how to utilize coroutines in C++20 to simplify asynchronous programming and make your code more readable and maintainable.
C++20, coroutines, asynchronous programming, cpp, modern C++, programming, code examples

#include <iostream>
#include <coroutine>

struct Generator {
    struct promise_type;
    using handle = std::coroutine_handle;

    struct promise_type {
        int current_value;

        auto get_return_object() {
            return Generator{handle::from_promise(*this)};
        }
        auto initial_suspend() { return std::suspend_always{}; }
        auto final_suspend() noexcept { return std::suspend_always{}; }
        void unhandled_exception() { std::terminate(); }
        auto yield_value(int value) {
            current_value = value;
            return std::suspend_always{};
        }
        void return_void() {}
    };

    handle coro;

    Generator(handle h) : coro(h) {}
    ~Generator() { coro.destroy(); }

    int next() {
        coro.resume();
        return coro.promise().current_value;
    }
};

Generator sequence() {
    for (int i = 0; i < 5; ++i) {
        co_yield i;
    }
}

int main() {
    auto gen = sequence();
    for (int i = 0; i < 5; ++i) {
        std::cout << gen.next() << std::endl;
    }
    return 0;
}
    

C++20 coroutines asynchronous programming cpp modern C++ programming code examples