std::experi...al::value_or(3)

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

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:

  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.

🧚 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.

πŸ”₯ 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