template< class U > constexpr T value_or( U&& default_value ) const&; | (since C++17) | |
template< class U > constexpr T value_or( U&& default_value ) &&; | (since C++17) |
Returns the contained value if *this
has a value, otherwise returns default_value
.
bool(*this) ? **this : static_cast<T>(std::forward<U>(default_value))
bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value))
default_value | - | the value to use in case *this is empty |
Type requirements | ||
-T must meet the requirements of CopyConstructible in order to use overload (1). |
||
-T must meet the requirements of MoveConstructible in order to use overload (2). |
||
-U&& must be convertible to T |
The current value if *this
has a value, or default_value
otherwise.
Any exception thrown by the selected constructor of the return value T
.
#include <optional> #include <iostream> #include <cstdlib> 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("MYPWD").value_or("(none)") << '\n'; }
Possible output:
(none)
returns the contained value (public member function) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/utility/optional/value_or