std::experimental::optional<T>::value_or
來自 cppreference.com
< cpp | experimental | optional
template< class U > constexpr T value_or( U&& default_value ) const&; |
(庫基礎 TS) | |
template< class U > constexpr T value_or( U&& default_value ) &&; |
(庫基礎 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))。
目錄 |
[編輯] 引數
default_value | - | 當 *this 為空時使用的值 |
型別要求 | ||
-為了使用過載 (1),T 必須滿足 可複製構造 (CopyConstructible) 的要求。 | ||
-為了使用過載 (2),T 必須滿足 可移動構造 (MoveConstructible) 的要求。 | ||
-U&& 必須可轉換為 T 。 |
[編輯] 返回值
如果 *this 包含一個值,則返回當前值,否則返回 default_value。
[編輯] 異常
由返回值 T
的選定建構函式丟擲的任何異常。
[編輯] 示例
執行此程式碼
#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)
[編輯] 參閱
返回所包含的值 (公共成員函式) |