Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add conversions between expected and optional #161

Open
malcolmdavey opened this issue Jul 15, 2024 · 0 comments
Open

Add conversions between expected and optional #161

malcolmdavey opened this issue Jul 15, 2024 · 0 comments

Comments

@malcolmdavey
Copy link

malcolmdavey commented Jul 15, 2024

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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant