◐ Shell
clean mode source ↗

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

来自cppreference.com

主模板

constexpr T& value() &;
(1) (C++23 起)
constexpr const T& value() const&;
(2) (C++23 起)
constexpr T&& value() &&;
(3) (C++23 起)
constexpr const T&& value() const&&;
(4) (C++23 起)

void 部分特化

constexpr void value() const&;
(5) (C++23 起)
constexpr void value() &&;
(6) (C++23 起)

如果 *this 包含预期值,那么返回到该预期值的引用。对于 void 部分特化不会返回值。

否则,抛出包含 error() 的副本的 std::bad_expected_access<std::decay_t<E>> 类型的异常。

1,2) 如果 std::is_copy_constructible_v<E>false,那么程序非良构。

3,4) 如果 std::is_copy_constructible_v<E>std::is_constructible_v<E, decltype(std::move(error()))>false,那么程序非良构。

5) 如果 std::is_copy_constructible_v<E>false,那么程序非良构。

6) 如果 std::is_move_constructible_v<E>false,那么程序非良构。

返回值

3,4) std::move(val)

异常

1,2,5)*this 包含非预期值时抛出 std::bad_expected_access(std::as_const(error()))

3,4,6)*this 包含非预期值时抛出 std::bad_expected_access(std::move(error()))

示例

可在 Compiler Explorer 上尝试。

#include <charconv>
#include <concepts>
#include <expected>
#include <print>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>

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

int main()
{
    try
    {
        auto result = to_int("42"); // 返回 std::expected{42}
        std::println("{}", result.value()); // 打印 42
        result = to_int("not a number"); // 返回 expected{unexpected{errc
       maybe_unused int x_x = result.value(); // 抛出异常
   }
   catch(const std::bad_expected_access<std::errc>& ex)
   {
       const std::errc ec{ex.error()};
       std::println("{}: {}", ex.what(), std::make_error_code(ec).message());
   }

} |p=true |output= 42 bad access to std::expected without expected value: Invalid argument }}

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 3940 C++23 重载 (5,6) 不需要 E 可复制/移动构造 需要

参阅