Namespaces
Variants

std::expected<T,E>:: operator bool, std::expected<T,E>:: has_value

From cppreference.net
Utilities library
constexpr explicit operator bool ( ) const noexcept ;
(1) (начиная с C++23)
constexpr bool has_value ( ) const noexcept ;
(2) (начиная с C++23)

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

Содержание

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

has_val

Примечания

Объект std::expected никогда не бывает пустым. Если has_value() возвращает true , operator*() может быть использован для доступа к ожидаемому значению; в противном случае, error() может быть использован для доступа к непредвиденному значению.

Пример

#include <charconv>
#include <concepts>
#include <cstdint>
#include <expected>
#include <print>
#include <string>
#include <string_view>
#include <system_error>
template<std::integral Int = int>
constexpr std::expected<Int, std::string> 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{std::move(std::make_error_code(ec).message())};
}
int main()
{
    if (auto result = to_int("42"); result.has_value())
        std::println("{}", *result); // после проверки безопасно использовать operator*
    else
        std::println("{}", result.error());
    if (const auto result = to_int("not a number"); result)
        std::println("{}", *result);
    else
        std::println("{}", result.error());
    if (const auto result{to_int<std::int16_t>("32768")}) // неявно вызывает (1)
        std::println("{}", *result);
    else
        std::println("{}", result.error());
}

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

42
Invalid argument
Numerical result out of range

Смотрите также

получает доступ к ожидаемому значению
(публичная функция-член)
возвращает неожиданное значение
(публичная функция-член)
проверяет, содержит ли объект значение
(публичная функция-член std::optional<T> )