#include #include #include #include #include #include #include // A program-defined type on which the coroutine_traits specializations below depend struct as_coroutine {}; // Enable the use of std::future as a coroutine type // by using a std::promise as the promise type. template requires(!std::is_void_v && !std::is_reference_v) struct std::coroutine_traits, as_coroutine, Args...> { struct promise_type : std::promise { std::future get_return_object() noexcept { return this->get_future(); } std::suspend_never initial_suspend() const noexcept { return {}; } std::suspend_never final_suspend() const noexcept { return {}; } void return_value(const T& value) noexcept(std::is_nothrow_copy_constructible_v) { this->set_value(value); } void return_value(T&& value) noexcept(std::is_nothrow_move_constructible_v) { this->set_value(std::move(value)); } void unhandled_exception() noexcept { this->set_exception(std::current_exception()); } }; }; // Same for std::future. template struct std::coroutine_traits, as_coroutine, Args...> { struct promise_type : std::promise { std::future get_return_object() noexcept { return this->get_future(); } std::suspend_never initial_suspend() const noexcept { return {}; } std::suspend_never final_suspend() const noexcept { return {}; } void return_void() noexcept { this->set_value(); } void unhandled_exception() noexcept { this->set_exception(std::current_exception()); } }; }; // Allow co_await'ing std::future and std::future // by naively spawning a new thread for each co_await. template auto operator co_await(std::future future) noexcept requires(!std::is_reference_v) { struct awaiter : std::future { bool await_ready() const noexcept { using namespace std::chrono_literals; return this->wait_for(0s) != std::future_status::timeout; } void await_suspend(std::coroutine_handle<> cont) const { std::thread([this, cont] { this->wait(); cont(); }).detach(); } T await_resume() { return this->get(); } }; return awaiter { std::move(future) }; } // Utilize the infrastructure we have established. std::future compute(as_coroutine) { int a = co_await std::async([] { return 6; }); int b = co_await std::async([] { return 7; }); co_return a * b; } std::future fail(as_coroutine) { throw std::runtime_error("bleah"); co_return; } int main() { std::cout << compute({}).get() << '\n'; try { fail({}).get(); } catch (const std::runtime_error& e) { std::cout << "error: " << e.what() << '\n'; } }