Spec-Zone.ru › C++

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

constexpr const E& error() const& noexcept;
(1) (начиная с C++23)
constexpr E& error() & noexcept;
(2) (начиная с C++23)
constexpr const E&& error() const&& noexcept;
(3) (начиная с C++23)
constexpr E&& error() && noexcept;
(4) (начиная с C++23)

Получает неожиданное значение, содержащееся в *this.

Если has_value() является true, поведение не определено.

(до C++26)

Если has_value() является true:

  • Если реализация защищена, происходит нарушение контракта.
  • Если реализация не защищена, поведение не определено.
(начиная с C++26)

Возвращаемое значение

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

Пример

#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
}

Возможный вывод:

1729
Invalid argument

См. также

error_or
возвращает неожиданное значение, если оно присутствует, иначе другое значение
(открытая функция-член)
operator->operator*
получает доступ к ожидаемому значению
(открытая функция-член)
value
возвращает ожидаемое значение
(открытая функция-член)
operator boolhas_value
проверяет, содержит ли объект ожидаемое значение
(открытая функция-член)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/utility/expected/error

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API