std::optional::or_else(3)
π NAME π
std::optional::or_else β std::optional::or_else, bestie. This is the std::optional::or_else(3) page from the C++ Standard Libary (that spelling is straight from the header, Iβm not fixing it π).
πΈ Synopsis πΈ
template< class F > (1) (since C++23)
constexpr optional or_else( F&& f ) const&;
template< class F > (2) (since C++23)
constexpr optional or_else( F&& f ) &&;
Okay so hereβs the vibe: it returns *this if it contains a value. Otherwise, it returns the result of f. Simple, iconic, no cap. π
The program is ill-formed if std::remove_cvref_t<std::invoke_result_t<F>> is not same as std::optional<T>. Like, that is a hard no from the compiler, bestie.
- Equivalent to
return *this ? *this : std::forward<F>(f)();. This overload participates in overload resolution only if bothstd::copy_constructible<T>andstd::invocable<F>are modeled. - Equivalent to
return *this ? std::move(*this) : std::forward<F>(f)();. This overload participates in overload resolution only if bothstd::move_constructible<T>andstd::invocable<F>are modeled.
π Parameters π
fβ a function or Callable object that returns anstd::optional<T>.
π¦ Return value π¦
*this or the result of f, as described above. Thatβs the whole flex. β¨
π Notes π
Feature-test macro moment, bestie:
__cpp_lib_optionalβ value202110L, standard(C++23), feature: Monadic operations instd::optional.
π Example π
// Run this code β yes, go run it:
#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
π See also π
value_orβ returns the contained value if available, another value otherwise (public member function).and_then(C++23)β returns the result of the given function on the contained value if it exists, or an empty optional otherwise (public member function).transform(C++23)β returns an optional containing the transformed contained value if it exists, or an empty optional otherwise (public member function).
π source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::optional::or_else(3) β thatβs the whole page, bestie, mwah! π
β¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms