0

I'd like to have a generator that terminates, like python, but I can't tell from ranges::views::generate's interface if this is supported.

Tom Huntington
  • 2,260
  • 10
  • 20

1 Answers1

0

You can roll it by hand easily enough: https://godbolt.org/z/xcGz6657r although it's probably better to use a coroutine generator if you have one available.

You can return an optional in the generator, and stop taking elements when a std::nullopt is generated with views::take_while

auto out = ranges::views::generate(
    [i = 0]() mutable -> std::optional<int>
    {
        if (i > 3)
            return std::nullopt;

        return { i++ };
    })
    | ranges::views::take_while([](auto opt){ return opt.has_value();})
    ;
Tom Huntington
  • 2,260
  • 10
  • 20