Skip to content

Instantly share code, notes, and snippets.

@bcardosolopes
Created November 4, 2020 01:47
#include <experimental/coroutine>
class resumable {
public:
struct promise_type;
using coro_handle = std::experimental::coroutine_handle<promise_type>;
resumable(coro_handle handle) : handle_(handle) { }
resumable(resumable&) = delete;
resumable(resumable&&) = delete;
bool resume() {
if (not handle_.done())
handle_.resume();
return not handle_.done();
}
~resumable() { handle_.destroy(); }
private:
coro_handle handle_;
};
struct resumable::promise_type {
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();
}
};
resumable foo() {
int x[10] = {};
int a = 3;
co_await std::experimental::suspend_always();
a++;
x[0] = 1;
a += 2;
x[1] = 2;
a += 3;
x[2] = 3;
}
int main(){
resumable res = foo();
while (res.resume());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment