std::optional<T>::transform

来自cppreference.com
< cpp‎ | utility‎ | optional
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
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::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),但 Ustd::remove_cv_t<std::invoke_result_t<F, const T&>>
3)Ustd::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),但 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

有些语言称此操作为映射(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 含值时返回自身,否则返回给定函数的结果
(公开成员函数)