std::optional<T>::or_else
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
std::optional
(C++26)
(C++26)
(C++23)
(C++23)
optional::or_else
(C++23)
template< class F >
constexpr optional or_else( F&& f ) const&;
(1)
(since C++23)
constexpr optional or_else( F&& f ) const&;
template< class F >
constexpr optional or_else( F&& f ) &&;
(2)
(since C++23)
constexpr optional or_else( F&& f ) &&;
Returns *this if it contains a value. Otherwise, returns the result of f.
The program is ill-formed if std::remove_cvref_t <std::invoke_result_t <F>> is not same as std::optional <T>.
1) Equivalent to return *this ? *this : std::forward <F>(f)();. This overload participates in overload resolution only if both std::copy_constructible <T> and std::invocable <F> are modeled.
2) Equivalent to return *this ? std::move(*this) : std::forward <F>(f)();. This overload participates in overload resolution only if both std::move_constructible <T> and std::invocable <F> are modeled.
Contents
[edit] Parameters
f
-
a function or Callable object that returns an std::optional <T>
[edit] Return value
*this or the result of f, as described above.
[edit] Notes
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_lib_optional |
202110L |
(C++23) | Monadic operations in std::optional |
[edit] Example
Run this code
#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: 0 Has value: 42 Valueless: 0
[edit] See also
(C++23)
optional
otherwise (public member function) [edit]