Modules and Coroutines
Modules and Coroutines
Understand what these C++20 features solve, where they help, and when to adopt them.
Modules and Coroutines
Understand what these C++20 features solve, where they help, and when to adopt them.
Headers work, but they come with repeated parsing, macro leakage, and fragile include boundaries. Modules aim to improve that.
export module math;
export int add(int a, int b) {
return a + b;
}
Consumers import the module instead of including a header:
import math;
Coroutines let a function suspend and resume, which is useful for async workflows and generators.
task<int> compute_answer() {
co_return 42;
}
The language feature alone is low-level. In practice you use coroutines through an abstraction provided by a framework or library.
generator<int> countdown(int from) {
while (from > 0) {
co_yield from--;
}
}
This is often the easiest coroutine shape to understand because each suspension point yields a sequence element.
co_await: suspend until another awaitable completesco_yield: produce the next value in a sequenceco_return: finish with a resultAdopt modules when your compiler and build system support them well. Adopt coroutines when you already have a real async or generator abstraction to build on. Both are powerful, but neither is a "turn it on everywhere" feature.