◐ Shell
clean mode source ↗

std::expected<T,E>::error - cppreference.com

来自cppreference.com

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 起)

返回值

3,4) std::move(unex )

示例

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

// 尝试将字符串转换为整数。
// 如果成功则返回整数,否则返回错误码。
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};
}

// 将字符串转换为整数。如果成功则打印整数并返回空(部分特化:expected<void, E>)。
// 否则,返回错误字符串。
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'; // 跳过

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

可能的输出:

参阅