std::expected<T,E>::value_or
Min standard notice:
Returns the expected value if it exists, otherwise returns default_value.
# Declarations
# Primary template
template< class U >
constexpr T value_or( U&& default_value ) const&;
(since C++23)
template< class U >
constexpr T value_or( U&& default_value ) &&;
(since C++23)
# Parameters
default_value: the value to use in case *this does not contain an expected value
# Return value
- For the
const&overload,has_value() ? **this : static_cast<T>(std::forward<U>(default_value)). - For the
&&overload,has_value() ? std::move(**this) : static_cast<T>(std::forward<U>(default_value)).
# Notes
These member functions exist only on the primary template. std::expected<void, E> does not provide value_or().
- The
const&overload requires thatTis copy-constructible and thatUis convertible toT; otherwise the program is ill-formed. - The
&&overload requires thatTis move-constructible and thatUis convertible toT; otherwise the program is ill-formed.
# Example
#include <expected>
#include <iostream>
#include <string>
std::expected<int, std::string> parse_port(bool ok)
{
if (ok)
return 8080;
return std::unexpected("invalid configuration");
}
int main()
{
std::cout << parse_port(true).value_or(80) << '\n';
std::cout << parse_port(false).value_or(80) << '\n';
}