std::optional::or_else(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– 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.

  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.

πŸŽ€ Parameters πŸŽ€

  • f β€” a function or Callable object that returns an std::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 β€” value 202110L, standard (C++23), feature: Monadic operations in std::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