The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <iostream>
#include <ranges>
#include "fibo3.hpp"
int main()
{
// initialize two different coroutines for Fibonacci numbers:
auto fibo5 = fibonacci(5); // first 5 Fibonacci numbers
auto fibo10 = fibonacci(10) | std::views::drop(3); // 4th to 10th Fibonacci number
// start both coroutines:
auto pos5 = fibo5.begin(); // RESUME first coroutine
auto pos10 = fibo10.begin(); // RESUME second coroutine \Bthree times
// iterate over the values as long as there is a value:
while (pos5 != fibo5.end() || pos10 != fibo10.end()) {
if (pos5 != fibo5.end()) {
std::cout << "fibo5: " << *pos5 << " ";
++pos5; // RESUME first coroutine
}
if (pos10 != fibo10.end()) {
std::cout << "fibo10: " << *pos10;
++pos10; // RESUME second coroutine
}
std::cout << '\n';
}
}