Namespaces
Variants

std::optional<T>:: value_or

From cppreference.net
Utilities library
template < class U = std:: remove_cv_t < T > >
constexpr T value_or ( U && default_value ) const & ;
(1) (since C++17)
template < class U = std:: remove_cv_t < T > >
constexpr T value_or ( U && default_value ) && ;
(2) (since C++17)

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

1) If std:: is_copy_constructible_v < T > && std:: is_convertible_v < U && , T > is false , the program is ill-formed.
2) If std:: is_move_constructible_v < T > && std:: is_convertible_v < U && , T > is false , the program is ill-formed.

Contents

Parameters

default_value - the value to be returned if * this does not contain a value

Return value

1) has_value ( ) ? ** this : static_cast < T > ( std:: forward < U > ( default_value ) ) ;
2) has_value ( ) ? std :: move ( ** this ) : static_cast < T > ( std:: forward < U > ( default_value ) )

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)

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3886 C++17 U does not have a default template argument specified

See also

returns the contained value
(public member function)