std::optional::value_or(3)
π
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.
- Equivalent to:
bool(*this) ? **this : static_cast<T>(std::forward<U>(default_value))
- Equivalent to:
bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value))
πΈ Parameters πΈ
default_valueβ the value to use in case*thisis empty. itβs the backup plan, the safety net, the βif not, then thisβ bestie π«Ά
π¦ Type requirements π¦
Tmust meet the requirements ofCopyConstructiblein order to use overload (1).Tmust meet the requirements ofMoveConstructiblein order to use overload (2).U&&must be convertible toT.
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 π
valuereturns 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
- 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