[ Web Proxy ]
URL:
Viewing: https://ru.cppreference.com/cpp/utility/optional/value_or [Back]  [Original]

std::optional<T>::value_or cppreference.com
cppreference.com

std::optional<T>::value_or

cppreference.com
 
C++
(C++20)
(C++20)
(C++11)
(C++20)
/
(C++11)
(C++11)
(C++11)
(C++17)
 
 
 
<tbody> </tbody>
template< class U > constexpr T value_or( U&& default_value ) const&;
(1) ( C++17)
template< class U > constexpr T value_or( U&& default_value ) &&;
(2) ( C++17)

, *this , default_value.

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

default_value , , *this
-
T CopyConstructible (1).
-
T MoveConstructible (2).
-
U&& T

, *this , default_value .

, T.

#include <optional>
#include <iostream>
#include <cstdlib>

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("()") << '\n';
     std::cout << maybe_getenv("MYPWD").value_or("()") << '\n';
}

:

/usr/bin/zsh
()


(public -) []

Web Proxy Viewer  |  New URL  |  Original Page