std::expected<T,E>::operator bool, std::expected<T,E>::has_value
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
Common vocabulary types
std::expected
expected::operator boolexpected::has_value
constexpr explicit operator bool() const noexcept;
(1)
(since C++23)
constexpr bool has_value() const noexcept;
(2)
(since C++23)
Checks whether *this represents an expected value.
Contents
[edit] Return value
[edit] Notes
A std::expected
object is never valueless. If has_value()
returns true, operator*()
can be used to access the expected value; otherwise, error()
can be used to access the unexpected value.
[edit] Example
Run this code
#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); // after the check it is safe to use 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")}) // implicitly calls (1) std::println ("{}", *result); else std::println ("{}", result.error()); }
Possible output:
42 Invalid argument Numerical result out of range