|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
| Iterators | ||||
(C++26) | ||||
(C++26) | ||||
| Monadic operations | ||||
(C++23) | ||||
(C++23) | ||||
optional::or_else (C++23) | ||||
| Modifiers | ||||
| Non-member functions | ||||
| Deduction guides | ||||
| Helper classes | ||||
| Helper objects | ||||
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>.
Contents |
| f | - | a function orCallable object that returns anstd::optional<T> |
*this or the result off, as described above.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_optional | 202110L | (C++23) | Monadic operations instd::optional |
#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
| 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] |