Forwarding c++ generators with cppcoro

Viewed 260

I want to write filters or transforms in the spirit of std::ranges::views but that take generators and return other generators. It is not clear to me what I can do with cppcoro generators and what the performance implications might be.

Given the simplest example like:

#include <cppcoro/generator.hpp>
#include <iostream>

cppcoro::generator<int> numbers(int begin, int end)
{
    for (int i = begin; i < end; ++i)
    {
        co_yield i;
    }
}

If we have a second generator that filters out factors of three:

template <typename Input>
cppcoro::generator<int> skip3s(Input input)
{
    for (auto key: input)
    {
        if (key % 3)
        {
            co_yield key;
        }
    }
}

We might compose them in a third function:

template <typename Input>
cppcoro::generator<int> wrapped_skip3s(Input input)
{
    return skip3s(std::move(input));
}

This compiles happily (https://godbolt.org/z/sGxYor) but

  1. Is it safe to forward a generator in this way?
  2. Should I be using cppcoro::recursive_generator and co_yield the inner generator?

The corountine examples I have come across have been very vanilla. In real life, I would expect my code using coroutines to end up like the rest of my codebase: composable, re-usable, with small functions and separation of concerns and results passed up and down the call stack.

Needless to say, the functions in the real world that I would like to use with coroutines have much more domain-specific complicated logic.

0 Answers
Related