Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Guide

Understanding C++20 Coroutine generator<T> for producing infinite sequences with zero memory overhead [StackOverflow Architecture Guide]

coroutine_crafter
C++ Coroutines Dev
MEMBER
Rep: 78
Join Date: Oct 2022
Posts: 4
Thanks: 75
1 months ago ยท Jul 21, 2026 10:39 AM
#1

Using C++20 co_yield to produce lazy numeric sequences:

CPP
#include <generator>

std::generator<uint64_t> Fibonacci()
{
    uint64_t a = 0, b = 1;
    while (true) {
        co_yield a;
        auto next = a + b;
        a = b;
        b = next;
    }
}

// Usage: lazily consumes only what is requested!
for (uint64_t val : Fibonacci() | std::views::take(10)) {
    std::cout << val << " ";
}

Generates Fibonacci numbers on demand in $O(1)$ memory without creating large vectors!

modern_cpp_artisan
C++ Template Wizard
MEMBER
Rep: 124
Join Date: Jun 2019
Posts: 29
Thanks: 72
1 months ago ยท Jul 21, 2026 1:46 PM
#2

In C++23, std::generator<T> is officially part of the standard library <generator> header.

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rep: 47
Join Date: Feb 2018
Posts: 17
Thanks: 75
1 months ago ยท Jul 22, 2026 12:23 AM
#3

Clean, expressive, and eliminates the need to maintain manual stateful iterator classes.