std::experi...al::value_or(3)
Okay so bestie, welcome to the std::experi...al::value_or(3) page β yes, that really is the delightfully truncated-looking title, and itβs filed under the C++ Standard Libary manual (their spelling, not mine π
). This is the std::experimental::optional::value_or situation, and weβre gonna get you fluent in it.
π NAME π
std::experi...al::value_orβ the page title vibe, exactly as printed.std::experimental::optional::value_orβ the full function name youβre actually here for.
π Synopsis π
Two overloads, both constexpr, both tagged (library fundamentals TS). Copy these exactly, bestie:
template< class U > (library fundamentals TS)
constexpr T value_or( U&& default_value ) const&;
template< class U > (library fundamentals TS)
constexpr T value_or( U&& default_value ) &&;
Returns the contained value if *this has a value, otherwise returns default_value.
Hereβs the tea on each overload:
- 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.
π§ 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.
π₯ 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.
β¨ Example β¨
The example starts with the classic // Run this code label β hereβs the whole thing, no cap:
#include <cstdlib>
#include <experimental/optional>
#include <iostream>
std::experimental::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("MYPWD").value_or("(none)") << '\n';
}
π¬ Possible output π¬
(none)
π See also π
valueβ returns the contained value (public member function).
ποΈ Category ποΈ
* Noindexed pagesβ yep, thatβs the category listing, asterisk and all.
Source/version/date cuteness: this page comes from http://cppreference.com, version 2024.06.10, and the footer title is std::experi...al::value_or(3). Love that for us. Bye bestie, go use value_or responsibly! π«Άπ
π¦ 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