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) | (seit C++23) |
|
constexpr
bool
has_value
(
)
const
noexcept
;
|
(2) | (seit C++23) |
Prüft, ob * this einen erwarteten Wert darstellt.
Inhaltsverzeichnis |
Rückgabewert
Hinweise
Ein
std::expected
-Objekt ist niemals wertlos. Wenn
has_value()
true
zurückgibt, kann
operator*()
verwendet werden, um auf den erwarteten Wert zuzugreifen; andernfalls kann
error()
verwendet werden, um auf den unerwarteten Wert zuzugreifen.
Beispiel
Diesen Code ausführen
#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); // nach der Prüfung ist die Verwendung von operator* sicher 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")}) // ruft implizit (1) auf std::println("{}", *result); else std::println("{}", result.error()); }
Mögliche Ausgabe:
42 Invalid argument Numerical result out of range
Siehe auch
|
greift auf den erwarteten Wert zu
(öffentliche Elementfunktion) |
|
|
gibt den unerwarteten Wert zurück
(öffentliche Elementfunktion) |
|
|
prüft, ob das Objekt einen Wert enthält
(öffentliche Elementfunktion von
std::optional<T>
)
|