Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::expected<T,E>::operator bool,std::expected<T,E>::has_value

      From cppreference.com
      <cpp‎ |utility‎ |expected
       
       
      Utilities library
       
       
      constexprexplicit operatorbool()constnoexcept;
      (1)(since C++23)
      constexprbool has_value()constnoexcept;
      (2)(since C++23)

      Checks whether*this represents an expected value.

      Contents

      [edit]Return value

      has_val

      [edit]Notes

      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.

      [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>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

      [edit]See also

      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 ofstd::optional<T>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/operator_bool&oldid=183385"

      [8]ページ先頭

      ©2009-2025 Movatter.jp