The co_yield Keyword

Understand the use of the 'co_yield' keyword in C++20.

We'll cover the following

Thanks to co_yield you can implement a generator generating an infinite data stream from which you can successively query values. The return type of the generator

generator<int> generatorForNumbers(int begin, int inc= 1)

is generator<int>, where generator internally holds a special promise p such that a call co_yield i is equivalent to a call co_await p.yield_value(i). Statement co_yield i can be called an arbitrary number of times. Immediately after each call, the execution of the coroutine is suspended.

An infinite data stream

The following program produces an infinite data stream. The coroutine getNext uses co_yield to create a data stream that starts at the start and gives on request the next value, incremented by step.

Get hands-on with 1200+ tech skills courses.