From the well-known C++ coroutine library (search "Don't allow any use of co_await inside the generator coroutine." in the source file generator.hpp), and from my own experiments, I know that a coroutine using co_yield cannot use co_await meanwhile.
Since a generator using co_yield must be synchronous, then, what's the advantage of using co_yield over a simple stateful lambda?
For example:
#include <iostream>
generator<int> g()
{
for (auto i = 0; i < 9; ++i)
{
co_yield i;
}
}
int main()
{
auto fn_gen = [i = 0] mutable { return i++; };
// Lambda way
for (auto i = 0; i < 9; ++i)
{
std::cout << fn_gen() << std::endl;
}
// co_yield way
for (auto i : g())
{
std::cout << i << std::endl;
}
}
What's the special value of co_yield in contrast to a simple stateful lambda in C++20?
Please See the Updated MWE: https://godbolt.org/z/x1Yoen7Ys
In the updated example, the output is totally unexpected when using co_await and co_yield in the same coroutine.