std::experimental::optional<T>::value_or
来自 cppreference.cn
< cpp | experimental | optional
template< class U > constexpr T value_or( U&& default_value ) const&; |
(library fundamentals TS) | |
template< class U > constexpr T value_or( U&& default_value ) &&; |
(library fundamentals TS) | |
如果 *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))。
目录 |
[edit] 参数
default_value | - | 当 *this 为空时使用的值 |
类型要求 | ||
-T 必须满足 CopyConstructible 的要求才能使用重载 (1)。 | ||
-T 必须满足 MoveConstructible 的要求才能使用重载 (2)。 | ||
-U&& 必须可转换为 T 。 |
[edit] 返回值
如果 *this 包含值,则返回当前值,否则返回 default_value。
[edit] 异常
返回值 T
的所选构造函数抛出的任何异常。
[edit] 示例
运行此代码
#include <cstdlib> #include <experimental/optional> #include <iostream> std::experimental::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)
[edit] 参见
返回包含的值 (公共成员函数) |