Debian Codegraph @

gcc/testsuite/g++.dg/coroutines/pr99047.C

raw
1 #include <optional>
2 #include <utility>
3 #include <coroutine>
4
5 template <typename T>
6 struct [[nodiscard]] task {
7 struct promise_type {
8 std::suspend_always initial_suspend() {
9 return {};
10 }
11 auto final_suspend() noexcept {
12 struct awaiter {
13 #if 1
14 std::false_type await_ready() noexcept {
15 return {};
16 }
17 #else
18 bool await_ready() noexcept {
19 return false;
20 }
21 #endif
22 std::coroutine_handle<> await_suspend(std::coroutine_handle<>) noexcept {
23 return next;
24 }
25 void await_resume() noexcept {
26 }
27 std::coroutine_handle<> next;
28 };
29 return awaiter{next};
30 }
31
32 void unhandled_exception() noexcept {
33 std::terminate();
34 }
35 auto get_return_object() {
36 return task(this);
37 }
38 auto coro() {
39 return std::coroutine_handle<promise_type>::from_promise(*this);
40 }
41 void return_value(T val) {
42 result.emplace(std::move(val));
43 }
44
45 std::coroutine_handle<> next;
46 std::optional<T> result;
47 };
48
49 task(task&& source) : p(std::exchange(source.p, nullptr)) {}
50 explicit task(promise_type* p) : p(p) {}
51 ~task() {
52 if (p)
53 p->coro().destroy();
54 }
55
56 bool await_ready() noexcept {
57 return p->coro().done();
58 }
59 std::coroutine_handle<> await_suspend(std::coroutine_handle<> next) noexcept {
60 p->next = next;
61 return p->coro();
62 }
63 const T& await_resume() const& noexcept {
64 return *p->result;
65 }
66
67 promise_type* p;
68 };
69
70 task<int> five() {
71 co_return 5;
72 }
73
74 task<int> six() {
75 co_return co_await five() + 1;
76 }
77
78
79 int main() {
80 auto task = six();
81 task.p->next = std::noop_coroutine();
82 task.p->coro().resume();
83 return *task.p->result;
84 }