std::optional<T>::transform
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
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));가 잘못된 형식이면 프로그램의 형식이 잘못되었습니다.
U가 std::remove_cv_t<std::invoke_result_t<F, const T&>>인 점이 다릅니다.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)));가 잘못된 형식이면 프로그램의 형식이 잘못되었습니다.
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) | 모나딕 연산 in 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
참고 항목
|
사용 가능한 경우 포함된 값을 반환하고, 그렇지 않으면 다른 값을 반환합니다
(public member function) |
|
|
(C++23)
|
값이 존재하는 경우 포함된 값에 대한 주어진 함수의 결과를 반환하고, 그렇지 않으면 빈
optional
을 반환합니다
(public member function) |
|
(C++23)
|
값이 포함된 경우
optional
자체를 반환하고, 그렇지 않으면 주어진 함수의 결과를 반환합니다
(public member function) |