Example of using a generator to generate Fibonacci numbers.
#include <iostream>
namespace {
{
int a = 0;
int b = 1;
if (n > 0) {
co_yield a;
}
if (n > 1) {
co_yield b;
}
for (int i = 2; i < n; ++i) {
auto s = a + b;
co_yield s;
a = b;
b = s;
}
}
}
int main()
{
std::cout << "The first 10 Fibonacci numbers are: ";
for (auto n : fibonacci(10)) {
std::cout << n << ' ';
}
std::cout << '\n';
return 0;
}
An synchronous generator that produces values of type Result.