Daily C++ Tip 4

A lazy pipeline with std::generator

A generator coroutine produces values only when the caller iterates.

A coroutine returning std::generator produces values on demand: nothing runs until the caller iterates, and nothing is stored.

#include <generator>
#include <iostream>

// Lazy: nothing runs until the caller iterates.
std::generator<int> evens(int upto) {
    for (int i = 0; i < upto; i += 2) co_yield i;
}

int main() {
    for (int v : evens(10)) std::cout << v << ' ';
    std::cout << '\n';
}

Observed output:

0 2 4 6 8

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.