命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | expected
 
 
 
 
主模板
template< class F >
constexpr auto and_then( F&& f ) &;
(1) (since C++23)
template< class F >
constexpr auto and_then( F&& f ) const&;
(2) (since C++23)
template< class F >
constexpr auto and_then( F&& f ) &&;
(3) (since C++23)
template< class F >
constexpr auto and_then( F&& f ) const&&;
(4) (since C++23)
void partial specialization
template< class F >
constexpr auto and_then( F&& f ) &;
(5) (since C++23)
template< class F >
constexpr auto and_then( F&& f ) const&;
(6) (since C++23)
template< class F >
constexpr auto and_then( F&& f ) &&;
(7) (since C++23)
template< class F >
constexpr auto and_then( F&& f ) const&&;
(8) (since 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 时,这些重载才参与重载解析。

目录

[编辑] 参数

f - 一个合适的函数或 Callable 对象,它返回一个 std::expected

[编辑] 返回值

 重载  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()))

[编辑] 注解

特性测试 Std 特性
__cpp_lib_expected 202211L (C++23) std::expected 的 Monadic 函数

[编辑] 示例

[编辑] 缺陷报告

以下行为变更缺陷报告已追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 3938 C++23 期望值通过 value() 获得[1] 更改为 **this
LWG 3973 C++23 期望值通过 **this 获得[2] 更改为 val
  1. value() 要求 E 是可复制构造的(参见 LWG issue 3843),而 operator* 则不然。
  2. **this 可以触发依赖于参数的查找

[编辑] 参见

expected 中非期望值的就地构造标签
(tag)[编辑]
如果存在,则返回一个包含转换后的期望值的 expected;否则,返回 expected 本身
(public member function) [编辑]