|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
expected::operator boolexpected::has_value | ||||
| Monadic operations | ||||
| Modifiers | ||||
| Non-member functions | ||||
| Helper classes | ||||
constexprexplicit operatorbool()constnoexcept; | (1) | (since C++23) |
constexprbool has_value()constnoexcept; | (2) | (since C++23) |
Checks whether*this represents an expected value.
Contents |
Astd::expected object is never valueless. Ifhas_value() returnstrue,operator*() can be used to access the expected value; otherwise,error() can be used to access the unexpected value.
#include <charconv>#include <concepts>#include <cstdint>#include <expected>#include <print>#include <string>#include <string_view>#include <system_error> template<std::integral Int=int>constexprstd::expected<Int,std::string> to_int(std::string_view str){ Int value{};constauto[_, ec]=std::from_chars(str.data(), str.data()+ str.size(), value);if(ec==std::errc())return value;returnstd::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*elsestd::println("{}", result.error()); if(constauto result= to_int("not a number"); result)std::println("{}",*result);elsestd::println("{}", result.error()); if(constauto result{to_int<std::int16_t>("32768")})// implicitly calls (1)std::println("{}",*result);elsestd::println("{}", result.error());}
Possible output:
42Invalid argumentNumerical result out of range
| accesses the expected value (public member function)[edit] | |
| returns the unexpected value (public member function)[edit] | |
| checks whether the object contains a value (public member function of std::optional<T>)[edit] |