co_yield is a C++ coroutine expression that produces a value, suspends execution, and lets the consumer resume the function later. A function containing co_yield becomes a coroutine when it returns a suitable task-like object. section 8.3.1 section 8.3.2
A co_yield expression connects several pieces of coroutine behavior:
- Passes its yielded value to yield_value in the coroutine's promise_type. section 8.3.5
- Suspends after yielding, returning control to the calling code. section 8.3.5
- Preserves local state so resumption continues on the statement after co_yield. section 8.3.2
- Works with co_return to finish the coroutine when no more values should be produced. section 8.3.2 section 8.3.5
Mind-reader coroutine
A game coroutine reads a player's choice, yields the choice together with the mind reader's prediction, and then updates its state after the caller resumes it. The caller reads the pair, displays the result, and calls next to continue. section 8.3.2 section 8.3.7
Listing 8.16 Our first coroutine
#include <coroutine>
struct Task; #1
Task coroutine_game() #2
{
std::mt19937 gen{ std::random_device{}() };
std::uniform_int_distribution dist{ 0, 1 };
MindReader mr(gen, dist);
while (true)
{
auto input = read_number(std::cin);
if (!input)
{
co_return; #3
}
int player_choice = input.value();
co_yield{ player_choice , mr.get_prediction() }; #4
mr.update(player_choice);
}
}
Inspect a complete coroutine function using co_yield and co_return, including the point where execution pauses. section 8.3.2
std::suspend_always yield_value(std::pair<int, int> got)
{
choice_and_prediction = got;
return {};
}
Inspect the promise_type method that stores a yielded pair and returns suspend_always to transfer control back to the caller. section 8.3.5
