std::expected<T,E>:: operator bool, std::expected<T,E>:: has_value
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::expected
| Member functions | ||||
| Observers | ||||
|
expected::operator bool
expected::has_value
|
||||
| Monadic operations | ||||
| Modifiers | ||||
| Non-member functions | ||||
| Helper classes | ||||
|
constexpr
explicit
operator
bool
(
)
const
noexcept
;
|
(1) | (C++23 이후) |
|
constexpr
bool
has_value
(
)
const
noexcept
;
|
(2) | (C++23 이후) |
* this 가 예상된 값을 나타내는지 확인합니다.
목차 |
반환값
참고 사항
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
참고 항목
|
기대값에 접근
(public member function) |
|
|
예상치 못한 값을 반환
(public member function) |
|
|
객체가 값을 포함하는지 확인
(
std::optional<T>
의 public member function)
|