Get the latest tech news

A Mental Model for C++ Coroutine


C++ coroutine is not a library that is ready to go (e.g. std::vector). It is not even a trait (think of Rust’s Future trait) that library writers or users can implement (or the compiler generates for you in the case of Rust). C++ coroutine is a specification that defines a set of customization points, that requires library writers to implement in order to get a functional coroutine.

Let us pretend to be a compiler for a second, the only thing that can be used to customize the behavior of the coroutine is really just the return type Task<T>. An obvious option here is to make Task<T> a subclass of some language defined interface (which owns the coroutine frame for storing state across co_await points), where a set of customization points can be implemented as member functions to specify the behavior of this coroutine. As we observed earlier, the return type Task<T> is the best entry-point for users to customize coroutine behaviors.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of mental model

mental model

Photo of c++ coroutine

c++ coroutine

Related news:

News photo

A mental model for Linux file, hard and soft links

News photo

My mental model of setf was wrong