名稱空間
變體
操作

std::expected<T,E>::or_else

來自 cppreference.com
< cpp‎ | 工具庫‎ | expected
 
 
 
 
主模板
template< class F >
constexpr auto or_else( F&& f ) &;
(1) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&;
(2) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) &&;
(3) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&&;
(4) (C++23 起)
void 偏特化
template< class F >
constexpr auto or_else( F&& f ) &;
(5) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&;
(6) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) &&;
(7) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&&;
(8) (C++23 起)

如果 *this 包含意外值,則以 *this 的意外值作為引數呼叫 f 並返回其結果。否則,返回表示期望值的 std::expected 物件。

1-4) 期望值用 *this 的期望值 val 初始化。

給定型別 G

1,2) std::remove_cvref_t<std::invoke_result_t<F, decltype(error())>>
3,4) std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(error()))>>
5,6) std::remove_cvref_t<std::invoke_result_t<F, decltype(error())>>
7,8) std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(error()))>>

如果 G 不是 std::expected 的特化,或 std::is_same_v<G::value_type, T>false,則程式格式錯誤。

1,2) 這些過載僅在 std::is_constructible_v<T, decltype((val))>true 時參與過載決議。
3,4) 這些過載僅在 std::is_constructible_v<T, decltype(std::move(val))>true 時參與過載決議。

目錄

[編輯] 引數

f - 一個合適的函式或 Callable 物件,它返回一個 std::expected

[編輯] 返回值

 過載  has_value() 的值
true false
(1,2) G(std::in_place, val) std::invoke(std::forward<F>(f), error())
(3,4) G(std::in_place, std::move(val)) std::invoke(std::forward<F>(f), std::move(error()))
(5,6) G() std::invoke(std::forward<F>(f), error())
(7,8) std::invoke(std::forward<F>(f), std::move(error()))

[編輯] 註解

特性測試 標準 特性
__cpp_lib_expected 202211L (C++23) std::expected 的單子函式

[編輯] 示例

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 3938 C++23 期望值是透過 value()[1] 獲得的 改為 **this
LWG 3973 C++23 期望值是透過 **this[2] 獲得的 改為 val
  1. value() 要求 E 是可複製構造的(參見 LWG issue 3843),而 operator* 不需要。
  2. **this 可以觸發 argument-dependent lookup

[編輯] 另見

如果 expected 包含預期值,返回 expected 自身;否則返回包含轉換後的非預期值的 expected
(公共成員函式) [編輯]