1 | #include <iostream>
|
---|
2 | #include <experimental/coroutine>
|
---|
3 |
|
---|
4 | struct suspend_never {
|
---|
5 | bool await_ready() noexcept {
|
---|
6 | return true;
|
---|
7 | }
|
---|
8 |
|
---|
9 | void await_suspend(std::experimental::coroutine_handle<>) noexcept {}
|
---|
10 | void await_resume() noexcept {}
|
---|
11 | };
|
---|
12 |
|
---|
13 | struct suspend_always {
|
---|
14 | bool await_ready() noexcept {
|
---|
15 | return false;
|
---|
16 | }
|
---|
17 |
|
---|
18 | void await_suspend(std::experimental::coroutine_handle<>) noexcept {}
|
---|
19 | void await_resume() noexcept {}
|
---|
20 | };
|
---|
21 |
|
---|
22 | struct counter_cor {
|
---|
23 | struct promise_type {
|
---|
24 | counter_cor get_return_object() {
|
---|
25 | return counter_cor(std::experimental::coroutine_handle<promise_type>::from_promise(*this));
|
---|
26 | }
|
---|
27 |
|
---|
28 | auto initial_suspend() { return suspend_never(); }
|
---|
29 | auto final_suspend() { return suspend_never(); }
|
---|
30 |
|
---|
31 | void return_void() {}
|
---|
32 |
|
---|
33 | void unhandled_exception() {}
|
---|
34 | };
|
---|
35 |
|
---|
36 | std::experimental::coroutine_handle<promise_type> _coroutine = nullptr;
|
---|
37 |
|
---|
38 | explicit counter_cor(std::experimental::coroutine_handle<promise_type> coroutine)
|
---|
39 | : _coroutine(coroutine)
|
---|
40 | {}
|
---|
41 |
|
---|
42 | ~counter_cor() {
|
---|
43 | if(_coroutine) { _coroutine.destroy(); }
|
---|
44 | }
|
---|
45 |
|
---|
46 | counter_cor() = default;
|
---|
47 | counter_cor(counter_cor const &) = delete;
|
---|
48 | counter_cor& operator=(counter_cor const &) = delete;
|
---|
49 |
|
---|
50 | counter_cor(counter_cor&& other) {
|
---|
51 | std::swap(_coroutine, other._coroutine);
|
---|
52 | }
|
---|
53 |
|
---|
54 | counter_cor& operator=(counter_cor&& other) {
|
---|
55 | if(&other != this) {
|
---|
56 | _coroutine = other._coroutine;
|
---|
57 | other._coroutine = nullptr;
|
---|
58 | }
|
---|
59 | return *this;
|
---|
60 | }
|
---|
61 |
|
---|
62 | void resume() { _coroutine.resume(); }
|
---|
63 | };
|
---|
64 |
|
---|
65 | counter_cor counter() {
|
---|
66 | std::cout << "Counter: called\n";
|
---|
67 | for(unsigned i = 1;; i++) {
|
---|
68 | co_await suspend_always{};
|
---|
69 | std::cout << "Counter: Resumed " << i << " time(s)\n";
|
---|
70 | }
|
---|
71 | }
|
---|
72 |
|
---|
73 | int main() {
|
---|
74 | std::cout << "Main: calling counter\n";
|
---|
75 | auto c = counter();
|
---|
76 | std::cout << "Main: resumes\n";
|
---|
77 | c.resume();
|
---|
78 | c.resume();
|
---|
79 | std::cout << "Main: done\n";
|
---|
80 | }
|
---|