std::optional<T>::transform
来自cppreference.com
<tbody>
</tbody>
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::optional。否则返回空 std::optional。
结果的所含值类型(以下以 U 代表)必须为非数组对象类型,且必须不是 std::in_place_t 或 std::nullopt_t。否则程序非良构。
1) 令
若变量定义
U 为 std::remove_cv_t<std::invoke_result_t<F, T&>>。若 *this 含值,则返回从 std::invoke(std::forward<F>(f), **this) 直接初始化所含值的 std::optional<U>(这与 and_then() 不同,它必须直接返回 std::optional)。否则返回空的 std::optional<U>。若变量定义
U x(std::invoke(std::forward<F>(f), **this)); 非良构则程序非良构。
2) 同 (1),但
U 为 std::remove_cv_t<std::invoke_result_t<F, const T&>>。3) 令
若变量定义
U 为 std::remove_cv_t<std::invoke_result_t<F, T>>。若 *this 含值,则返回从 std::invoke(std::forward<F>(f), std::move(**this)) 直接初始化所含值的 std::optional<U> 。否则返回空的 std::optional<U>。若变量定义
U x(std::invoke(std::forward<F>(f), std::move(**this))); 非良构则程序非良构。
4) 同 (3),但
U 为 std::remove_cv_t<std::invoke_result_t<F, const T>>。参数
| f | - | 适合的函数或可调用 (Callable) 对象 |
返回值
含有 f 的结果的 std::optional 或空 std::optional,如上所述。
注解
因为 transform 直接在正确的位置构造 U 对象,而非将它传递给构造函数,所以 std::is_move_constructible_v<U> 可以为 false。
有些语言称此操作为映射(map)。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_optional |
202110L |
(C++23) | std::optional 中的单子式操作 |
示例
运行此代码
#include <iostream>
#include <optional>
struct A { /* ... */ };
struct B { /* ... */ };
struct C { /* ... */ };
struct D { /* ... */ };
auto A_to_B(A) -> B { /* ... */ std::cout << "A => B \n"; return {}; }
auto B_to_C(B) -> C { /* ... */ std::cout << "B => C \n"; return {}; }
auto C_to_D(C) -> D { /* ... */ std::cout << "C => D \n"; return {}; }
void try_transform_A_to_D(std::optional<A> o_A)
{
std::cout << (o_A ? "o_A 含值\n" : "o_A 为空\n");
std::optional<D> o_D = o_A.transform(A_to_B)
.transform(B_to_C)
.transform(C_to_D);
std::cout << (o_D ? "o_D 含值\n\n" : "o_D 为空\n\n");
};
int main()
{
try_transform_A_to_D( A{} );
try_transform_A_to_D( {} );
}
输出:
o_A 含值
A => B
B => C
C => D
o_D 含值
o_A 为空
o_D 为空
参阅
| 在所含值可用时返回它,否则返回另一个值 (公开成员函数) | |
(C++23) |
在所含值存在时返回对其应用给定的函数的结果,否则返回空的 optional (公开成员函数) |
(C++23) |
在 optional 含值时返回自身,否则返回给定函数的结果 (公开成员函数) |