std::optional<T>::transform
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)。否则程序非良构。
U 为 std::remove_cv_t<std::invoke_result_t<F, T&>>。如果 *this 含值,则返回一个 std::optional<U>,其值通过 直接初始化自 std::invoke(std::forward<F>(f), **this) 得到(与 and_then() 不同,后者必须直接返回 std::optional)。否则返回空的 std::optional<U>。
- 如果变量定义
U x(std::invoke(std::forward<F>(f), **this));非良构,则程序非良构。
U 为 std::remove_cv_t<std::invoke_result_t<F, const T&>>。U 为 std::remove_cv_t<std::invoke_result_t<F, T>>。如果 *this 含值,则返回一个 std::optional<U>,其值通过直接初始化自 std::invoke(std::forward<F>(f), std::move(**this)) 得到。否则返回空的 std::optional<U>。
- 如果变量定义
U x(std::invoke(std::forward<F>(f), std::move(**this)));非良构,则程序非良构。
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
。
由于可调用对象
f
无法返回引用类型,因此它不能是
指向数据成员的指针
。
某些语言将此操作称为 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 has a value\n" : "o_A is empty\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 has a value\n\n" : "o_D is empty\n\n"); }; int main() { try_transform_A_to_D( A{} ); try_transform_A_to_D( {} ); }
输出:
o_A has a value A => B B => C C => D o_D has a value o_A is empty o_D is empty
参见
|
若存在被容纳值则返回该值,否则返回另一值
(公开成员函数) |
|
|
(C++23)
|
若存在被容纳值则返回给定函数在该值上的结果,否则返回空的
optional
(公开成员函数) |
|
(C++23)
|
若
optional
本身包含值则返回它,否则返回给定函数的结果
(公开成员函数) |