std::optional<T>::or_else
來自 cppreference.com
template< class F > constexpr optional or_else( F&& f ) const&; |
(1) | (C++23 起) |
template< class F > constexpr optional or_else( F&& f ) &&; |
(2) | (C++23 起) |
如果包含值,則返回 *this。否則,返回 f 的結果。
如果 std::remove_cvref_t<std::invoke_result_t<F>> 與 std::optional<T> 不同,則程式格式錯誤。
1) 等價於 return *this ? *this : std::forward<F>(f)();。此過載僅在同時建模 std::copy_constructible<T> 和 std::invocable<F> 時參與過載決議。
2) 等價於 return *this ? std::move(*this) : std::forward<F>(f)();。此過載僅在同時建模 std::move_constructible<T> 和 std::invocable<F> 時參與過載決議。
目錄 |
[編輯] 引數
f | - | 一個函式或 可呼叫 (Callable) 物件,它返回一個 std::optional<T> |
[編輯] 返回值
如上所述,返回 *this 或 f 的結果。
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_optional |
202110L |
(C++23) | std::optional 中的單子操作 |
[編輯] 示例
執行此程式碼
#include <iostream> #include <optional> #include <string> int main() { using maybe_int = std::optional<int>; auto valueless = [] { std::cout << "Valueless: "; return maybe_int{0}; }; maybe_int x; std::cout << x.or_else(valueless).value() << '\n'; x = 42; std::cout << "Has value: "; std::cout << x.or_else(valueless).value() << '\n'; x.reset(); std::cout << x.or_else(valueless).value() << '\n'; }
輸出
Valueless: 0 Has value: 42 Valueless: 0
[編輯] 參閱
如果可用,返回包含的值,否則返回另一個值 (public 成員函式) | |
(C++23) |
如果存在包含的值,則返回給定函式對該值的結果,否則返回空的 optional (public 成員函式) |
(C++23) |
如果存在包含的值,則返回一個包含轉換後的值的 optional ,否則返回一個空的 optional (public 成員函式) |