Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

Guide

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

coroutine_crafter
C++ Coroutines Dev
MEMBER
担当者: 78
参加日: Oct 2022
投稿: 4
ありがとう: 75
1 か月前 · 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
担当者: 124
参加日: Jun 2019
投稿: 29
ありがとう: 72
1 か月前 · 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
担当者: 47
参加日: Feb 2018
投稿: 17
ありがとう: 75
1 か月前 · Jul 22, 2026 12:23 AM
#3

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