std::optional::value_or(3)

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

πŸ’… std::optional::value_or(3) β€” C++ Standard Libary bestie energy ✨

okay so bestie, this page is literally the β€œgive me the thing or give me the fallback” icon. no cap. it’s std::optional::value_or o’clock and we’re obsessed.

πŸŽ€ NAME πŸŽ€

std::optional::value_or - std::optional::value_or. that’s the name, that’s the vibe, periodt.

✨ Synopsis ✨

template< class U >                               (1) (since C++17)
constexpr T value_or( U&& default_value ) const&;
template< class U >                               (2) (since C++17)
constexpr T value_or( U&& default_value ) &&;

Returns the contained value if *this has a value, otherwise returns default_value.

  1. Equivalent to:
bool(*this) ? **this : static_cast<T>(std::forward<U>(default_value))
  1. Equivalent to:
bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value))

🌸 Parameters 🌸

  • default_value β€” the value to use in case *this is empty. it’s the backup plan, the safety net, the β€œif not, then this” bestie 🫢

πŸ¦‹ Type requirements πŸ¦‹

  • T must meet the requirements of CopyConstructible in order to use overload (1).
  • T must meet the requirements of MoveConstructible in order to use overload (2).
  • U&& must be convertible to T.

ngl these are the β€œcheck yourself before you wreck yourself” rules. no vibes-based skipping, bestie πŸ’€

πŸ“ Return value πŸ“

The current value if *this has a value, or default_value otherwise.

πŸ”₯ Exceptions πŸ”₯

Any exception thrown by the selected constructor of the return value T.

so if that chosen constructor of T throws, it is not being swallowed β€” it’s coming through, and we respect it 😭✨

🧚 Example 🧚

// Run this code

#include <cstdlib>
#include <iostream>
#include <optional>

std::optional<const char*> maybe_getenv(const char* n)
{
    if (const char* x = std::getenv(n))
        return x;
    else
        return {};
}

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)

that’s the possible output listed on the page β€” iconic, honestly πŸ’–

πŸ‘‘ See also πŸ‘‘

  • value returns the contained value (public member function).

sign-off time, bestie: this page is from http://cppreference.com, version 2024.06.10, dated 2024.06.10, for std::optional::value_or(3). slay, hydrate, and may your optionals always have a value when you need one πŸ’œπŸŽ€

πŸ“¦ where this page comes from