std::optional<T>::value_or
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
std::optional
optional::value_or
(C++26)
(C++26)
(C++23)
(C++23)
(C++23)
template< class U = std::remove_cv_t <T> >
constexpr T value_or( U&& default_value ) const&;
(1)
(since C++17)
constexpr T value_or( U&& default_value ) const&;
template< class U = std::remove_cv_t <T> >
constexpr T value_or( U&& default_value ) &&;
(2)
(since C++17)
constexpr T value_or( U&& default_value ) &&;
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.
[edit] Parameters
default_value
-
the value to be returned if *this does not contain a value
[edit] 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))
[edit] Example
Run this code
#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] 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 |