Modules and Coroutines

Modules and Coroutines

Understand what these C++20 features solve, where they help, and when to adopt them.

Modules and Coroutines

Modules

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;

What changes in practice

When modules help

When to be careful

Coroutines

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-style coroutines

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.

The three keywords

Adoption advice

Adopt 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.

Exercises