|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
optional::value_or | ||||
| Iterators | ||||
(C++26) | ||||
(C++26) | ||||
| Monadic operations | ||||
(C++23) | ||||
(C++23) | ||||
(C++23) | ||||
| Modifiers | ||||
| Non-member functions | ||||
| Deduction guides | ||||
| Helper classes | ||||
| Helper objects | ||||
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.
Contents |
| default_value | - | the value to be returned if*this does not contain a value |
#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)
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 |
| returns the contained value (public member function)[edit] |