Search code examples
c++std-rangesstd-expected

How to return a range::view in a std::expected?


Is there a way to return a range::view in a std::expected construct? For example, in the pseudo code below, what can I write instead of the rangeType?

std::expected<rangeType, error> get_range()
{
    if (some_condition(x))
        return std::unexpected(errorcode);

    return data|ranges::views::take(x);
}

Solution

  • When returning a std::expected<DifficultTypeToSpell, E> from a function, one can avoid spelling the type entirely, by using the monadic interface of std::expected. Start with a std::expected<T, E> which contains either the actual error, or some default constructed T (which could even be void), and transform it with the expression that actually gives you the type that's difficult to spell.

    So the code could look something like this:

    auto get_range()
    {
        return [] -> std::expected<void, error> {   // start with a simple type
            if (some_condition(x)) 
                return std::unexpected(error{});
            return {};
        }().transform([] {    // and then transform to the desired type
                return data | std::ranges::views::take(x);
        });
    }