std::optional<T>::value_or
cppreference.com
<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 -) |