Request Short Link
C++ 98
C++ 11
C++ 14
C++ 17
C++ 20
C++ 23
C++ 2c
for-loops as while-loops
array subscription
Show all implicit casts
Show all template parameters of a CallExpr
Use libc++
Transform std::initializer_list
Show noexcept internals
Show padding information
Show coroutine transformation
Show C++ to C transformation
Show object lifetime
Default
15
18
20
22
26
More
GitHub
Patreon
Issues
About
Policies
Examples
C++ Insights @ YouTube
Settings
Version
New C++ Insights Episode
×
Made by
Andreas Fertig
Powered by
Flask
and
CodeMirror
Source:
#include <experimental/coroutine> #include <iostream> #include <cassert> using namespace std; class resumable { public: struct promise_type; using coro_handle = std::experimental::coroutine_handle<promise_type>; resumable(coro_handle handle) : handle_(handle) { assert(handle); } resumable(resumable&) = delete; resumable(resumable&&) = delete; bool resume() { if (not handle_.done()) handle_.resume(); return not handle_.done(); } const char* return_val(); ~resumable() { handle_.destroy(); } private: coro_handle handle_; }; struct resumable::promise_type { const char* string_; void return_value(const char* string) {string_ = string;} using coro_handle = std::experimental::coroutine_handle<promise_type>; auto get_return_object() { return coro_handle::from_promise(*this); } auto initial_suspend() { return std::experimental::suspend_always(); } auto final_suspend() noexcept { return std::experimental::suspend_always(); } // void return_void() {} void unhandled_exception() { std::terminate(); } }; const char* resumable::return_val(){ return handle_.promise().string_; } resumable foo(){ std::cout << "Hello" << std::endl; co_await std::experimental::suspend_always(); std::cout << "World" << std::endl; co_return "Coroutine"; } int main(){ resumable res = foo(); while (res.resume()); std::cout << res.return_val() << std::endl; }
Insight:
Console: