std::optional<T>::value_or
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |   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 为空情况的值
 | 
| 类型要求 | ||
 - 为使用重载 (1) , T 必须满足可复制构造 (CopyConstructible)  的要求。
 | ||
 - 为使用重载 (2) , T 必须满足可移动构造 (MoveConstructible)  的要求。
 | ||
 -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("MYPWD").value_or("(none)") << '\n'; }
可能的输出:
(none)
参阅
|    返回所含值  (公开成员函数)  |