std::expected<T,E>::error - cppreference.com
From cppreference.com
constexpr const E& error() const& noexcept; |
(1) | (since C++23) |
constexpr E& error() & noexcept; |
(2) | (since C++23) |
constexpr const E&& error() const&& noexcept; |
(3) | (since C++23) |
constexpr E&& error() && noexcept; |
(4) | (since C++23) |
Accesses the unexpected value contained in *this.
|
If has_value() is |
(until C++26) |
|
If has_value() is
|
(since C++26) |
Return value
3,4) std::move(unex )
Example
#include <charconv> #include <concepts> #include <expected> #include <iostream> #include <string> #include <string_view> #include <system_error> // Try to convert string to integer. If success, // return integer, otherwise return an error code. 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}; } // Convert string to integer. If success, print the integer and return nothing // (partial specialization: expected<void, E>). Otherwise, return an error string. std::expected<void, std::string> print_as_int(std::string_view str) { if (auto result = to_int(str)) { std::cout << *result << '\n'; return {}; } else return std::unexpected{std::make_error_code(result.error()).message()}; } int main() { if (const auto result{print_as_int("1729")}; not result) std::cout << result.error() << '\n'; // skipped if (const auto result{print_as_int("NaN")}; not result) std::cout << result.error() << '\n'; // prints error }
Possible output: