std::optional<T>::transform
來自 cppreference.com
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 x(std::invoke(std::forward<F>(f), **this)); 格式錯誤,則程式格式錯誤。
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)); 格式錯誤,則程式格式錯誤。
3) 令
如果變數定義 U x(std::invoke(std::forward<F>(f), std::move(**this))); 格式錯誤,則程式格式錯誤。
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))); 格式錯誤,則程式格式錯誤。
目錄 |
[編輯] 引數
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 本身,否則返回給定函式的結果(公共成員函式) |