CKTIS / C++
std::generator: lazy coroutine-backed range
C++23 std::generator turns a co_yield coroutine into a movable, single-pass range that produces elements on demand.
Version: C++23
Syntax
template<class Ref, class Value = void, class Allocator = void>
class std::generator;
// A coroutine returning std::generator<T> can use:
co_yield expression;
// std::generator models std::ranges::view and std::ranges::input_range.std::generator<Ref> from <generator> is both a view and an input range. A coroutine function returning it can use co_yield; calling that function creates its frame but leaves the body initially suspended. The first begin() resumes execution to the first value, and incrementing the iterator resumes to the next co_yield or completion. Elements need not be materialized in a container beforehand.
The squares() coroutine in the example computes squares only as iteration asks for them. Each co_yield value * value suspends with the next result; the range-for loop copies 1, 4, and 9, so it prints 1 4 9. The temporary generator lives for the complete loop, and its destructor destroys the coroutine frame. Breaking the loop early also destroys the unexecuted remainder safely.
std::generator is movable, non-copyable, and models only input_range: do not assume multipass traversal or retain a yielded reference after advancing its iterator. Calling begin() more than once on the same generator has undefined behavior. An unhandled body exception emerges from the iteration operation that resumed the coroutine; frame allocation can throw std::bad_alloc. Objects referred to by co_yield must live across the relevant suspension. std::ranges::elements_of can lazily flatten a compatible generator or range, and the allocator parameter controls frame storage.
Examples
#include <generator>
#include <iostream>
std::generator<int> squares() {
for (int value = 1; value <= 3; ++value) {
co_yield value * value;
}
}
int main() {
bool first = true;
for (int value : squares()) {
if (!first) std::cout << ' ';
std::cout << value;
first = false;
}
std::cout << '\n';
}
Result
1 4 9
std::generator → 1 4 9