| 1 |
#if !__has_include(<coroutine>) \ |
| 2 |
&& __has_include(<experimental/coroutine>) // for __clang__ |
| 3 |
#include <experimental/coroutine> |
| 4 |
namespace std { |
| 5 |
using namespace std::experimental; |
| 6 |
} |
| 7 |
#else |
| 8 |
#include <coroutine> |
| 9 |
#endif |
| 10 |
#include <optional> |
| 11 |
|
| 12 |
struct future |
| 13 |
{ |
| 14 |
using value_type = int; |
| 15 |
struct promise_type; |
| 16 |
using handle_type = std::coroutine_handle<promise_type>; |
| 17 |
|
| 18 |
handle_type _coroutine; |
| 19 |
|
| 20 |
future(handle_type h) : _coroutine{h} {} |
| 21 |
|
| 22 |
~future() noexcept{ |
| 23 |
if (_coroutine) { |
| 24 |
_coroutine.destroy(); |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
value_type get() { |
| 29 |
auto ptr = _coroutine.promise()._value; |
| 30 |
return *ptr; |
| 31 |
} |
| 32 |
|
| 33 |
struct promise_type { |
| 34 |
std::optional<value_type> _value = std::nullopt; |
| 35 |
|
| 36 |
future get_return_object() { |
| 37 |
return future{handle_type::from_promise(*this)}; |
| 38 |
} |
| 39 |
void return_value(value_type val) { |
| 40 |
_value = static_cast<value_type &&>(val); |
| 41 |
} |
| 42 |
auto initial_suspend() noexcept { |
| 43 |
class awaiter { |
| 44 |
std::optional<value_type> & value; |
| 45 |
public: |
| 46 |
explicit awaiter(std::optional<value_type> & val) noexcept : value{val} {} |
| 47 |
bool await_ready() noexcept { return value.has_value(); } |
| 48 |
void await_suspend(handle_type) noexcept { } |
| 49 |
value_type & await_resume() noexcept { return *value; } |
| 50 |
}; |
| 51 |
|
| 52 |
return awaiter{_value}; |
| 53 |
} |
| 54 |
std::suspend_always final_suspend() noexcept { |
| 55 |
return {}; |
| 56 |
} |
| 57 |
//void return_void() {} |
| 58 |
void unhandled_exception() {} |
| 59 |
}; |
| 60 |
}; |
| 61 |
|
| 62 |
future create_future() |
| 63 |
{ co_return 2021; } |
| 64 |
|
| 65 |
int main() |
| 66 |
{ auto f = create_future(); } |