Coroutines are powerful but require some boilerplate code. Quasar Chunawala explains what you need to implement to get coroutines working.
Coroutines – A Deep Dive
by Quasar Chunawala
From the article:
Following on from the introduction in the editorial, let’s understand the basic mechanics needed to code up a simple coroutine, and I’ll show you how to yield from the coroutine and await results.
The simplest coroutine
The following code is the simplest implementation of a coroutine:
#include <coroutine> void coro_func(){ co_return; } int main(){ coro_func(); }Our first coroutine will just return nothing. It will not do anything else. Sadly, the preceding code is too simple for a functional coroutine and it will not compile. When compiling with gcc 15.2, we get the error shown in Figure 1.
Looking at C++ reference, we see that the return type of a coroutine must define a type named
<source>: In function 'void coro_func()': <source>:4:5: error: unable to find the promise type for this coroutine 4 | co_return; | ^~~~~~~~~promise_type. Why do we need a promise? Thepromise_typeis the second important piece in the coroutine mechanism. We can draw an analogy from futures and promises which are essential blocks for achieving asynchronous programming in C++. The future is the thing, that the function that does the asynchronous computation, hands out back to the caller, that the caller can use to retrieve the result by invoking theget()member function. The future has the role of the return object.

Add a Comment
Comments are closed.