Namespaces
Variants

std::expected<T,E>::error

From cppreference.com
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
 
constexpr const E& error() const& noexcept;
(1) (since C++23)
constexpr E& error() & noexcept;
(2) (since C++23)
constexpr const E&& error() const&& noexcept;
(3) (since C++23)
constexpr E&& error() && noexcept;
(4) (since C++23)

Accesses the unexpected value contained in *this.

If has_value() is true, the behavior is undefined.

(until C++26)

If has_value() is true:

(since C++26)

Return value

1,2) unex
3,4) std::move(unex )

Example

#include <charconv>
#include <concepts>
#include <expected>
#include <iostream>
#include <string>
#include <string_view>
#include <system_error>

// Try to convert string to integer. If success,
// return integer, otherwise return an error code.
template<std::integral Int = int>
constexpr std::expected<Int, std::errc> to_int(std::string_view str)
{
    Int value{};
    const auto [_, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
    if (ec == std::errc())
        return value;
    return std::unexpected{ec};
}

// Convert string to integer. If success, print the integer and return nothing
// (partial specialization: expected<void, E>). Otherwise, return an error string.
std::expected<void, std::string> print_as_int(std::string_view str)
{
    if (auto result = to_int(str))
    {
        std::cout << *result << '\n';
        return {};
    }
    else
        return std::unexpected{std::make_error_code(result.error()).message()};
}

int main()
{
    if (const auto result{print_as_int("1729")}; not result)
        std::cout << result.error() << '\n'; // skipped

    if (const auto result{print_as_int("NaN")}; not result)
        std::cout << result.error() << '\n'; // prints error
}

Possible output:

1729
Invalid argument

See also

returns the unexpected value if present, another value otherwise
(public member function) [edit]
accesses the expected value
(public member function) [edit]
returns the expected value
(public member function) [edit]
checks whether the object contains an expected value
(public member function) [edit]