std::optional::value_or - cppreference.com (original) (raw)

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 returns default_value.

[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

#include #include #include   std::optional<const char*> maybe_getenv(const char* n) { if (const char* x = std::getenv(n)) return x; else return {}; }   int main() { std::cout << maybe_getenv("SHELL").value_or("(none)") << '\n'; std::cout << maybe_getenv("MYPWD").value_or("(none)") << '\n'; }

Possible output:

[edit] Defect reports

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

DR Applied to Behavior as published Correct behavior
LWG 3886 C++17 U does not have a default template argument specified

[edit] See also

| | returns the contained value (public member function) [edit] | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |