命名空间
变体
操作

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>>

目录

[编辑] 参数

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 包含值,则返回 optional 本身,否则返回给定函数的结果
(公共成员函数) [编辑]