//******************************************************** // The following code example is taken from the book // C++23 - The Complete Guide // by Nicolai M. Josuttis (www.josuttis.com) // http://www.cppstd23.com // // The code is licensed under a // Creative Commons Attribution 4.0 International License // http://creativecommons.org/licenses/by/4.0/ //******************************************************** #include #include #include std::generator coro() { std::cout << "\t** coro(): yield 1" << std::endl; co_yield 1; // SUSPEND with 1 std::cout << "\t** coro(): yield 2" << std::endl; co_yield 2; // SUSPEND with 2 std::cout << "\t** coro(): THROW" << std::endl; throw std::runtime_error{"error in coroutine"}; // EXCEPTION std::cout << "\t** coro(): not reached" << std::endl; } int main() { auto gen = coro(); std::cout << "begin(): " << std::endl; auto pos = gen.begin(); // START coroutine while (pos != gen.end()) { std::cout << "got: " << *pos << std::endl; std::cout << "++pos: " << std::endl; try { ++pos; // RESUME coroutine } catch (const std::exception& e) { std::cout << "EXCEPTION: " << e.what() << std::endl; } } std::cout << "at end()" << std::endl; }