Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::expected

      From cppreference.com
      <cpp‎ |utility
       
       
      Utilities library
       
       
      Defined in header<expected>
      template<class T,class E>
      class expected;
      (1)(since C++23)
      template<class T,class E>

          requiresstd::is_void_v<T>

      class expected<T, E>;
      (2)(since C++23)

      The class templatestd::expected provides a way to represent either of two values: anexpected value of typeT, or anunexpected value of typeE.expected is never valueless.

      1) The main template. Contains the expected or unexpected value within its own storage, which isnested within theexpected object.
      2) Thevoid partial specialization. Represents an expectedvoid value or contains an unexpected value. If it contains an unexpected value, it is nested within theexpected object.

      A program is ill-formed if it instantiates anexpected with a reference type, a function type, or a specialization ofstd::unexpected. In addition,T must not bestd::in_place_t orstd::unexpect_t.

      Contents

      [edit]Template parameters

      T - the type of the expected value. The type must either be (possibly cv-qualified)void, or meet theDestructible requirements (in particular, array and reference types are not allowed).
      E - the type of the unexpected value. The type must meet theDestructible requirements, and must be a valid template argument forstd::unexpected (in particular, arrays, non-object types, and cv-qualified types are not allowed).

      [edit]Nested types

      Type Definition
      value_typeT
      error_typeE
      unexpected_typestd::unexpected<E>

      [edit]Member templates

      Template Definition
      rebind<U>std::expected<U, error_type>

      [edit]Data members

      Member Description
      boolhas_val whether theexpected object currently represents the expected value
      (exposition-only member object*)
      Tval(main template only) the expected value
      (exposition-only variant member object*)
      Eunex the unexpected value
      (exposition-only variant member object*)

      [edit]Member functions

      constructs theexpected object
      (public member function)[edit]
      destroys theexpected object, along with its contained value
      (public member function)[edit]
      assigns contents
      (public member function)[edit]
      Observers
      accesses the expected value
      (public member function)[edit]
      checks whether the object contains an expected value
      (public member function)[edit]
      returns the expected value
      (public member function)[edit]
      returns the unexpected value
      (public member function)[edit]
      returns the expected value if present, another value otherwise
      (public member function)[edit]
      returns the unexpected value if present, another value otherwise
      (public member function)[edit]
      Monadic operations
      returns the result of the given function on the expected value if it exists; otherwise, returns theexpected itself
      (public member function)[edit]
      returns anexpected containing the transformed expected value if it exists; otherwise, returns theexpected itself
      (public member function)[edit]
      returns theexpected itself if it contains an expected value; otherwise, returns the result of the given function on the unexpected value
      (public member function)[edit]
      returns theexpected itself if it contains an expected value; otherwise, returns anexpected containing the transformed unexpected value
      (public member function)[edit]
      Modifiers
      constructs the expected value in-place
      (public member function)[edit]
      exchanges the contents
      (public member function)[edit]

      [edit]Non-member functions

      (C++23)
      comparesexpected objects
      (function template)[edit]
      specializes thestd::swap algorithm
      (function)[edit]

      [edit]Helper classes

      (C++23)
      represented as an unexpected value
      (class template)[edit]
      exception indicating checked access to anexpected that contains an unexpected value
      (class template)[edit]
      in-place construction tag for unexpected value inexpected
      (tag)[edit]

      [edit]Notes

      Types with the same functionality are calledResult in Rust andEither in Haskell.

      Feature-test macroValueStdFeature
      __cpp_lib_expected202202L(C++23)class templatestd::expected and associatedhelper classes
      202211L(C++23)Monadic functions forstd::expected

      [edit]Example

      Run this code
      #include <cmath>#include <expected>#include <iomanip>#include <iostream>#include <string_view> enumclass parse_error{    invalid_input,    overflow}; auto parse_number(std::string_view& str)-> std::expected<double, parse_error>{constchar* begin= str.data();char* end;double retval=std::strtod(begin,&end); if(begin== end)returnstd::unexpected(parse_error::invalid_input);elseif(std::isinf(retval))returnstd::unexpected(parse_error::overflow);     str.remove_prefix(end- begin);return retval;} int main(){auto process=[](std::string_view str){std::cout<<"str: "<<std::quoted(str)<<", ";if(constauto num= parse_number(str); num.has_value())std::cout<<"value: "<<*num<<'\n';// If num did not have a value, dereferencing num// would cause an undefined behavior, and// num.value() would throw std::bad_expected_access.// num.value_or(123) uses specified default value 123.elseif(num.error()== parse_error::invalid_input)std::cout<<"error: invalid input\n";elseif(num.error()== parse_error::overflow)std::cout<<"error: overflow\n";elsestd::cout<<"unexpected!\n";// or invoke std::unreachable();}; for(auto src:{"42","42abc","meow","inf"})        process(src);}

      Output:

      str: "42", value: 42str: "42abc", value: 42str: "meow", error: invalid inputstr: "inf", error: overflow

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 4141C++23the requirement of storage
      allocation was confusing
      the contained object must be
      nested within theexpected object

      [edit]References

      • C++23 standard (ISO/IEC 14882:2024):
      • 22.8 Expected objects [expected]

      [edit]See also

      (C++17)
      a type-safe discriminated union
      (class template)[edit]
      (C++17)
      a wrapper that may or may not hold an object
      (class template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected&oldid=182339"

      [8]ページ先頭

      ©2009-2025 Movatter.jp