C++ Library Extensions
2022.12.09
To help learn modern C++ programming
033-coroutine.cpp
Go to the documentation of this file.
1
#include "
033-coroutine.hpp
"
2
3
//ResumableType<int>
4
resumable_type<int>
addition
(
int
a,
int
b)
5
{
6
// co_return expression
7
// calls PromiseType::return_value(expression)
8
co_return
a + b;
9
}
10
11
void
test_co_return
()
12
{
13
auto
add =
addition
(2, 3);
14
15
add.resume();
16
17
std::cout
<< add.get() <<
std::endl
;
18
}
19
20
// ResumableType<int>
21
resumable_type<int>
summation
(
int
max)
22
{
23
int
s = 0;
24
for
(
int
i=1; i < max; ++i)
25
{
26
s += i;
27
28
co_yield
s;
29
}
30
31
co_return
s;
32
}
33
34
void
test_co_yield
()
35
{
36
auto
co_sum =
summation
(11);
37
38
while
(co_sum.resume())
39
{
40
std::cout
<< co_sum.get() <<
std::endl
;
41
}
42
}
43
44
// ResumableType<int>
45
resumable_type<int>
factorial
(
int
max)
46
{
47
int
f = 1;
48
49
for
(
int
i=1; i < max; ++i)
50
{
51
f *= i;
52
53
auto
s =
co_await
f;
54
55
std::cout
<< s <<
std::endl
;
56
}
57
58
std::cout
<< f <<
std::endl
;
59
60
co_return
f;
61
}
62
63
void
test_co_await
()
64
{
65
auto
f =
factorial
(11);
66
67
while
(f.resume());
68
}
69
70
// ResumableType<void>
71
resumable_type<>
72
no_return_value_coroutine
(
int
max)
73
{
74
for
(
int
i=0; i < max; ++i)
75
{
76
co_await
i;
77
78
std::cout
<< i <<
std::endl
;
79
}
80
81
co_return
;
82
}
83
84
void
test_no_return_value_coroutine
()
85
{
86
auto
no_return =
no_return_value_coroutine
(11);
87
88
while
(no_return.resume());
89
}
90
91
int
main
()
92
{
93
test_co_return
();
94
95
test_co_yield
();
96
97
test_co_await
();
98
99
test_no_return_value_coroutine
();
100
}
no_return_value_coroutine
resumable_type no_return_value_coroutine(int max)
Definition:
033-coroutine.cpp:72
test_co_await
void test_co_await()
Definition:
033-coroutine.cpp:63
test_co_return
void test_co_return()
Definition:
033-coroutine.cpp:11
summation
resumable_type< int > summation(int max)
Definition:
033-coroutine.cpp:21
addition
resumable_type< int > addition(int a, int b)
Definition:
033-coroutine.cpp:4
test_co_yield
void test_co_yield()
Definition:
033-coroutine.cpp:34
factorial
resumable_type< int > factorial(int max)
Definition:
033-coroutine.cpp:45
main
int main()
Definition:
033-coroutine.cpp:91
test_no_return_value_coroutine
void test_no_return_value_coroutine()
Definition:
033-coroutine.cpp:84
033-coroutine.hpp
cout
auto & cout
Definition:
044-functional.cpp:3
endl
auto & endl
Definition:
apply_operations.cpp:32
ResumableType
Definition:
033-coroutine.hpp:52
CppExtension
tutorial
033-coroutine.cpp
Generated by
1.9.4