Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::optional<T>::value_or

      From cppreference.com
      <cpp‎ |utility‎ |optional
       
       
      Utilities library
       
       
      template<class U=std::remove_cv_t<T>>
      constexpr T value_or( U&& default_value)const&;
      (1)(since C++17)
      template<class U=std::remove_cv_t<T>>
      constexpr T value_or( U&& default_value)&&;
      (2)(since C++17)

      Returns the contained value if*this contains a value, otherwise returnsdefault_value.

      1) Ifstd::is_copy_constructible_v<T>&&std::is_convertible_v<U&&, T> isfalse, the program is ill-formed.
      2) Ifstd::is_move_constructible_v<T>&&std::is_convertible_v<U&&, T> isfalse, the program is ill-formed.

      Contents

      [edit]Parameters

      default_value - the value to be returned if*this does not contain a value

      [edit]Return value

      1)has_value()?**this:static_cast<T>(std::forward<U>(default_value));
      2)has_value()? std::move(**this):static_cast<T>(std::forward<U>(default_value))

      [edit]Example

      Run this code
      #include <cstdlib>#include <iostream>#include <optional> std::optional<constchar*> maybe_getenv(constchar* n){if(constchar* x=std::getenv(n))return x;elsereturn{};} int main(){std::cout<< maybe_getenv("SHELL").value_or("(none)")<<'\n';std::cout<< maybe_getenv("MYPWD").value_or("(none)")<<'\n';}

      Possible output:

      /usr/bin/zsh(none)

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      LWG 3886C++17U does not have a default template argumentspecified

      [edit]See also

      returns the contained value
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional/value_or&oldid=180657"

      [8]ページ先頭

      ©2009-2025 Movatter.jp