Last active
May 19, 2022 08:37
-
-
Save Dugy/5899399ba9c69b95e1cd394d9919c92d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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