命名空间
变体
操作

std::optional<T>::transform

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
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_tstd::nullopt_t。 否则,程序为非良构。

1)Ustd::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)); 为非良构,则程序为非良构。
2)(1) 相同,除了 Ustd::remove_cv_t<std::invoke_result_t<F, const T&>>
3)Ustd::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))); 为非良构,则程序为非良构。
4)(3) 相同,除了 Ustd::remove_cv_t<std::invoke_result_t<F, const T>>

目录

[edit] 参数

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

[edit] 返回值

一个 std::optional,含有 f 的结果,或者一个空的 std::optional,如上所述。

[edit] 注解

因为 transform 直接在正确的位置构造 U 对象,而不是将其传递给构造函数,所以 std::is_move_constructible_v<U> 可以为 false

由于可调用对象 f 不能返回引用类型,它不能是指向数据成员的指针

一些语言将此操作称为 map(映射)。

特性测试 Std 特性
__cpp_lib_optional 202110L (C++23) std::optional 中的 单子操作

[edit] 示例

#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

[edit] 参见

返回所含值(如果可用),否则返回另一值
(公开成员函数) [编辑]
(C++23)
返回在所含值上给定函数的结果(如果存在),否则返回空的 optional
(公开成员函数) [编辑]
(C++23)
如果 optional 含有值则返回自身,否则返回给定函数的结果
(公开成员函数) [编辑]