From cppreference.com
constexprexplicitoperatorbool()constnoexcept; (1) (since C++23)constexprboolhas_value()constnoexcept; (2) (since C++23)Checks whether *this represents an expected value.
Return value
Notes
A
object is never valueless. If has_value() returns true,
can be used to access the expected value; otherwise,
can be used to access the unexpected value.
Example
Can be checked out on
.
Run this code
#include<charconv>#include<concepts>#include<cstdint>#include<expected>#include<print>#include<string>#include<string_view>#include<system_error>#include<utility>template<std::integralInt=int>constexprstd::expected<Int,std::string>to_int(std::string_viewstr){Intvalue{};constauto[_,ec]=std::from_chars(str.data(),str.data()+str.size(),value);if(ec==std::errc())returnvalue;returnstd::unexpected{std::move(std::make_error_code(ec).message())};}intmain(){if(autoresult=to_int("42");result.has_value())std::println("{}",*result);// after the check it is safe to use operator*elsestd::println("{}",result.error());if(constautoresult=to_int("not a number");result)std::println("{}",*result);elsestd::println("{}",result.error());if(constautoresult{to_int<std::int16_t>("32768")})// implicitly calls (1)std::println("{}",*result);elsestd::println("{}",result.error());}Possible output:
42 Invalid argument Numerical result out of range See also