我从 github 存储库的 cppcoro 库中看到了这段代码:
cppcoro::async_generator<int> ticker(int count, threadpool& tp)
{
for (int i = 0; i < count; ++i)
{
co_await tp.delay(std::chrono::seconds(1));
co_yield i;
}
}
cppcoro::task<> consumer(threadpool& tp)
{
auto sequence = ticker(10, tp);
for co_await (std::uint32_t i : sequence)
{
std::cout << "Tick " << i << std::endl;
}
}
其中async_generator
产生一个值 while 可以co_await
和协程consumer
具有for co_await
其中的等价性:
for co_await (std::uint32_t i : sequence) {
std::cout << "Tick " << i << std::endl;
}
是
{
auto&& __range = sequence;
auto __begin = co_await __range.begin();
auto __end = __range.end();
for (; __begin != __end; co_await ++__begin) {
std::uint32_t i = *__begin;
std::cout << "Tick " << i << std::endl;
}
}
根据协程 TS 草案:http ://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4775.pdf
for co_await
C++20 不发货的原因是什么?