Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::optional<T>::or_else

      From cppreference.com
      <cpp‎ |utility‎ |optional
       
       
      Utilities library
       
       
      template<class F>
      constexpr optional or_else( F&& f)const&;
      (1)(since C++23)
      template<class F>
      constexpr optional or_else( F&& f)&&;
      (2)(since C++23)

      Returns*this if it contains a value. Otherwise, returns the result off.

      The program is ill-formed ifstd::remove_cvref_t<std::invoke_result_t<F>> is not same asstd::optional<T>.

      1) Equivalent toreturn*this?*this:std::forward<F>(f)();. This overload participates in overload resolution only if bothstd::copy_constructible<T> andstd::invocable<F> are modeled.
      2) Equivalent toreturn*this? std::move(*this):std::forward<F>(f)();. This overload participates in overload resolution only if bothstd::move_constructible<T> andstd::invocable<F> are modeled.

      Contents

      [edit]Parameters

      f - a function orCallable object that returns anstd::optional<T>

      [edit]Return value

      *this or the result off, as described above.

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_optional202110L(C++23)Monadic operations instd::optional

      [edit]Example

      Run this code
      #include <iostream>#include <optional>#include <string> int main(){using maybe_int=std::optional<int>; auto valueless=[]{std::cout<<"Valueless: ";return maybe_int{0};};     maybe_int x;std::cout<< x.or_else(valueless).value()<<'\n';     x=42;std::cout<<"Has value: ";std::cout<< x.or_else(valueless).value()<<'\n';     x.reset();std::cout<< x.or_else(valueless).value()<<'\n';}

      Output:

      Valueless: 0Has value: 42Valueless: 0

      [edit]See also

      returns the contained value if available, another value otherwise
      (public member function)[edit]
      (C++23)
      returns the result of the given function on the contained value if it exists, or an emptyoptional otherwise
      (public member function)[edit]
      (C++23)
      returns anoptional containing the transformed contained value if it exists, or an emptyoptional otherwise
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional/or_else&oldid=171477"

      [8]ページ先頭

      ©2009-2025 Movatter.jp