Namespaces
Variants

std::optional<T>:: transform

From cppreference.net
Utilities library
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:: optional < U > ,其内含值通过 直接初始化 std:: invoke ( std:: forward < F > ( f ) , ** this ) (与必须直接返回 std::optional and_then() 不同)。否则返回空的 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:: 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) 相同,不同之处在于 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 本身包含值则返回它,否则返回给定函数的结果
(公开成员函数)