Skip to content

Instantly share code, notes, and snippets.

@Dugy
Last active May 19, 2022 08:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dugy/5899399ba9c69b95e1cd394d9919c92d to your computer and use it in GitHub Desktop.
Save Dugy/5899399ba9c69b95e1cd394d9919c92d to your computer and use it in GitHub Desktop.
#ifndef RESUMABLE_BY_DUGI
#define RESUMABLE_BY_DUGI
#include <coroutine>
#include <stdexcept>
struct CallToFinsihedCoroutine : public std::logic_error {
using std::logic_error::logic_error;
};
template <typename T>
class Resumable {
public:
struct promise_type {
T _returned;
auto get_return_object() {
return handle_type::from_promise(*this);
}
auto initial_suspend() {
return std::suspend_always();
}
auto final_suspend() {
return std::suspend_always();
}
void unhandled_exception() {
throw std::current_exception();
}
auto yield_value(const T& value){
_returned = value;
return std::suspend_always();
}
void return_value(const T& value) {
_returned = value;
}
};
using handle_type = std::coroutine_handle<promise_type>;
Resumable(handle_type handle) : _handle(handle) { }
Resumable(const Resumable&) = delete;
T operator()() {
if (_handle.done())
throw CallToFinsihedCoroutine("Call to finished coroutine");
_handle.resume();
return _handle.promise()._returned;
}
explicit operator bool() {
return !_handle.done();
}
~Resumable() {
_handle.destroy();
}
private:
handle_type _handle;
};
#endif // RESUMABLE_BY_DUGI
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment