C++ Library Extensions 2022.12.09
To help learn modern C++ programming
032-coroutine.cpp
Go to the documentation of this file.
1#include "032-coroutine.hpp"
2
3// this is our first corountine
4template<typename SemanticReturnType>
6sum(SemanticReturnType a, SemanticReturnType b)
7{
8 // co_return expression
9 // terminates the coroutine
10
11 co_yield a * b;
12
13 co_yield a + b;
14
15 co_return (a + b)*( a - b);
16}
17
19{
20 // at this point, our corountine co_sum
21 // is initially suspended
22 ResumableType<int> co_sum = sum(2, 3);
23
24 co_sum.resume();
25
26 std::cout <<"sum(2,3) = "
27 << co_sum.get() << std::endl;
28
29 co_sum.resume();
30
31 std::cout <<"sum(2,3) = "
32 << co_sum.get() << std::endl;
33
34 co_sum.resume();
35
36 std::cout <<"sum(2,3) = "
37 << co_sum.get() << std::endl;
38
39}
40
41template<typename SemanticReturnType>
43summation(SemanticReturnType max)
44{
45 SemanticReturnType s = 0;
46
47 for(SemanticReturnType i = 0;
48 i < max; ++i)
49 {
50 s += i;
51 co_yield s;
52 }
53
54 co_return s;
55}
56
58{
59 auto cosum = summation(11);
60
61 for(int i=0; i < 11; ++i)
62 {
63 std::cout << cosum.next() << std::endl;
64 }
65}
66
67int main()
68{
69 // test_coroutine_basic();
71}
void test_coroutine_basic()
ResumableType< SemanticReturnType > sum(SemanticReturnType a, SemanticReturnType b)
ResumableType< SemanticReturnType > summation(SemanticReturnType max)
void advanced_coroutine()
int main()
auto & cout
auto & endl
SemanticReturnType get()