ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change
on this file since be3416d was
be3416d,
checked in by tdelisle <tdelisle@…>, 5 years ago
|
Added more examples of c++20 coroutines
|
-
Property mode set to
100644
|
File size:
1.4 KB
|
Rev | Line | |
---|
[be3416d] | 1 | |
---|
| 2 | #include "base.hpp" |
---|
| 3 | |
---|
| 4 | struct fmt_cor { |
---|
| 5 | struct promise_type { |
---|
| 6 | char * _value = nullptr; |
---|
| 7 | |
---|
| 8 | fmt_cor get_return_object() { |
---|
| 9 | return fmt_cor(std::experimental::coroutine_handle<promise_type>::from_promise(*this)); |
---|
| 10 | } |
---|
| 11 | |
---|
| 12 | auto initial_suspend() { return suspend_never(); } |
---|
| 13 | auto final_suspend() { |
---|
| 14 | return suspend_always(); |
---|
| 15 | } |
---|
| 16 | |
---|
| 17 | void return_void() {} |
---|
| 18 | |
---|
| 19 | auto yield_value(char & value) { |
---|
| 20 | _value = &value; |
---|
| 21 | return suspend_always(); |
---|
| 22 | } |
---|
| 23 | |
---|
| 24 | void unhandled_exception() {} |
---|
| 25 | }; |
---|
| 26 | |
---|
| 27 | std::experimental::coroutine_handle<promise_type> _coroutine = nullptr; |
---|
| 28 | |
---|
| 29 | explicit fmt_cor(std::experimental::coroutine_handle<promise_type> coroutine) |
---|
| 30 | : _coroutine(coroutine) |
---|
| 31 | {} |
---|
| 32 | |
---|
| 33 | ~fmt_cor() { |
---|
| 34 | if(_coroutine) { _coroutine.destroy(); } |
---|
| 35 | } |
---|
| 36 | |
---|
| 37 | fmt_cor() = default; |
---|
| 38 | fmt_cor(fmt_cor const &) = delete; |
---|
| 39 | fmt_cor& operator=(fmt_cor const &) = delete; |
---|
| 40 | |
---|
| 41 | fmt_cor(fmt_cor&& other) { |
---|
| 42 | std::swap(_coroutine, other._coroutine); |
---|
| 43 | } |
---|
| 44 | |
---|
| 45 | fmt_cor& operator=(fmt_cor&& other) { |
---|
| 46 | if(&other != this) { |
---|
| 47 | _coroutine = other._coroutine; |
---|
| 48 | other._coroutine = nullptr; |
---|
| 49 | } |
---|
| 50 | return *this; |
---|
| 51 | } |
---|
| 52 | |
---|
| 53 | void send(char a) { |
---|
| 54 | assert(_coroutine.promise()._value); |
---|
| 55 | *_coroutine.promise()._value = a; |
---|
| 56 | _coroutine.resume(); |
---|
| 57 | } |
---|
| 58 | }; |
---|
| 59 | |
---|
| 60 | fmt_cor Fmt() { |
---|
| 61 | char c; |
---|
| 62 | int g, b; |
---|
| 63 | for(;;) { |
---|
| 64 | for(g = 0; g < 5; g++) { |
---|
| 65 | for(b = 0; b < 4; b++) { |
---|
| 66 | co_yield c; |
---|
| 67 | std::cout << c; |
---|
| 68 | } |
---|
| 69 | std::cout << " "; |
---|
| 70 | } |
---|
| 71 | std::cout << std::endl; |
---|
| 72 | } |
---|
| 73 | } |
---|
| 74 | |
---|
| 75 | int main() { |
---|
| 76 | auto fmt = Fmt(); |
---|
| 77 | for(int i = 0; i < 41; i++) { |
---|
| 78 | fmt.send('a'); |
---|
| 79 | } |
---|
| 80 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.