名稱空間
變體
操作

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

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

如果 *this 表示一個期望值,則呼叫 f 並返回其結果。否則,返回一個包含非期望值的 std::expected 物件,該物件用 *this 的非期望值進行初始化。

1-4) f 以期望值 val 作為引數被呼叫。
5-8) f 不帶任何引數被呼叫。

給定型別 U

1,2) std::remove_cvref_t<std::invoke_result_t<F, decltype((val))>>
3,4) std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(val))>>

如果 U 不是 std::expected 的特化,或者 std::is_same_v<U::error_type, E>false,則程式格式錯誤。

1,2) 這些過載只有在 std::is_constructible_v<E, decltype(error())>true 時才參與過載決議。
3,4) 這些過載只有在 std::is_constructible_v<E, decltype(std::move(error()))>true 時才參與過載決議。
5,6) 這些過載只有在 std::is_constructible_v<E, decltype(error())>true 時才參與過載決議。
7,8) 這些過載只有在 std::is_constructible_v<E, decltype(std::move(error()))>true 時才參與過載決議。

目錄

[edit] 引數

f - 一個合適的函式或 可呼叫 物件,返回一個 std::expected

[edit] 返回值

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

[edit] 注意

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

[edit] 示例

[edit] 缺陷報告

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

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

[edit] 另請參閱

用於 expected 中非預期值就地構造的標籤
(標籤)[編輯]
如果預期值存在,返回包含轉換後的預期值的 expected;否則返回 expected 自身
(公共成員函式) [編輯]