TartanLlama / expected

C++11/14/17 std::expected with functional-style extensions
https://tl.tartanllama.xyz
Creative Commons Zero v1.0 Universal
1.55k stars 135 forks source link

Add conversions between expected and optional #161

Open malcolmdavey opened 4 months ago

malcolmdavey commented 4 months ago

Sometimes it might he handy to drop the error, or maybe add an error, from previous expected/optional values, returns. This may be also when needing to conform to an existing interface.

Not sure if these would be best methods or stand alone functions, but might be nicer methods, similar to the monadic methods.

template <class T>
class optional
{
public:
    template < class E>
    expected<T, E> to_expected(E&& error) const&;
    template < class E>
    expected<T, E> to_expected(E&& error) &&;
};

template <class T, class E>
class expected
{
public:
    optional<T> to_optional() const&;
    optional<T> to_optional() &&;
};

Would need overloads or use C++23 explicit this.

Alternative names as_optional, as_expected

Here are basic implementations of a stand alone functions which would work for now (might not be strictly correct/ideal in terms of move/forward rvalue ref etc), just to give basic idea.

template <class T>
optional<T> to_optional(expected<T,E>&& result)
{
    if (result.has_value())
        return forward(result.value());

    return {};
}

template <class T, class E>
expected<T,E> to_expected(optional<T>&& result, E&& error)
{
    if (result.has_value())
        return expected<T, E>(std::forward(result.value()));

    return unexpected(std::forward(error));
}