Namespaces
Variants

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

从 zh.cppreference.net
 
 
 
 
template< class F >
constexpr auto transform( F&& f ) &;
(1) (C++23 起)
template< class F >
constexpr auto transform( F&& f ) const&;
(2) (C++23 起)
template< class F >
constexpr auto transform( F&& f ) &&;
(3) (C++23 起)
template< class F >
constexpr auto transform( F&& f ) const&&;
(4) (C++23 起)

如果 *this 包含一个期望值,则调用 f 并返回一个包含其结果的 std::expected 对象;否则,返回一个包含 std::expected 副本的 error() 对象。

如果 T 不是(可能有 cv 限定)void,则包含的值(operator*())作为参数传递给 f;否则 f 不接受参数。

令 U 为:

  • 如果 T 不是(可能有 cv 限定)void:
    • 对于重载 (1-2), std::remove_cv_t<std::invoke_result_t<F, decltype(operator*())>>;
    • 对于重载 (3-4), std::remove_cv_t<std::invoke_result_t<F, decltype(std::move(operator*()))>>;
  • 否则(T 可能有 cv 限定 void),则 std::remove_cv_t<std::invoke_result_t<F>>。

U必须是 std::expected 的有效值类型。类型 U 的变量必须可从调用结果构造(但无需可移动构造)。返回类型为 std::expected<U, E>。

1-2) 仅在 std::is_constructible_v<E, decltype(error())> 为 true 时参与重载决议。
3-4) 仅在 std::is_constructible_v<E, decltype(std::move(error()))> 为 true 时参与重载决议。

形式上,这些函数执行以下步骤:

  • 如果 *this 包含期望值 val:
  1. 调用 f,如同:
    • std::invoke(std::forward<F>(f), val) 对于重载 (1,2) ,如果 std::is_void_v<T> 是 false;
    • std::invoke(std::forward<F>(f), std::move(val)) 对于重载 (3,4),如果 std::is_void_v<T> 是 false;
    • std::invoke(std::forward<F>(f)) 如果 std::is_void_v<T> 是 true。
  2. 然后:
    • 如果 std::is_void_v<U> 是 false,则返回一个包含期望值的 std::expected 对象,该期望值直接初始化自调用结果;
    • 否则,返回 std::expected<U, E>()。
  • 否则(*this 包含错误值),返回 std::expected<U, E>(std::unexpect, error())。

参数

f - 一个合适的函数或 Callable 对象,其调用签名返回非引用类型

返回值

给定表达式 expr 为:

1,2) std:: invoke ( std:: forward < F > ( f ) , val )
3,4) std:: invoke ( std:: forward < F > ( f ) ,std :: move ( val ) )
5-8) std:: invoke ( std:: forward < F > ( f ) )

返回值定义如下:

重载版本 has_value() 的值
true false
( 1,2 ) std:: expected < U, E > ( std:: unexpect , error ( ) )
( 3,4 ) std:: expected < U, E >
( std:: unexpect , std :: move ( error ( ) ) )
( 5,6 ) std:: expected < U, E > ( std:: unexpect , error ( ) )
( 7,8 ) std:: expected < U, E >
( std:: unexpect , 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 问题 3843 ),而 operator* 无此要求。
  2. ↑ ** this 可能触发 实参依赖查找 。

参见

若当前 expected 包含期望值则返回其自身;否则返回包含转换后非期望值的 expected
(公开成员函数)