Namespaces
Variants
Views
Actions

std::optional<T>::value_or

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
Utilities library
Language support
Type support (basic types, RTTI)
Library feature-test macros (C++20)
Dynamic memory management
Program utilities
Coroutine support (C++20)
Variadic functions
Debugging support
(C++26)
Three-way comparison
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)

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

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)).
2) Equivalent to bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value)).

Contents

[edit] 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.

[edit] Return value

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

[edit] Exceptions

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

[edit] Example

#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)

[edit] See also

returns the contained value
(public member function) [edit]