命名空间
变体
操作

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

来自 cppreference.cn
< 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 自身
(公共成员函数) [编辑]