std::expected<T,E>::transform
template< class F >
constexpr auto transform( F&& f ) &;
|
(1) | (since C++23) |
template< class F >
constexpr auto transform( F&& f ) const&;
|
(2) | (since C++23) |
template< class F >
constexpr auto transform( F&& f ) &&;
|
(3) | (since C++23) |
template< class F >
constexpr auto transform( F&& f ) const&&;
|
(4) | (since C++23) |
If *this contains an expected value, invokes f and returns a std::expected object that contains its result; otherwise, returns a std::expected object that contains a copy of error().
If T is not (possibly cv-qualified) void, the contained value (operator*()) is passed as an argument to f; otherwise f takes no argument.
Let U be:
- if
Tis not (possibly cv-qualified)void:- for overloads (1-2),
std::remove_cv_t<std::invoke_result_t<F, decltype(operator*())>>; - for overloads (3-4),
std::remove_cv_t<std::invoke_result_t<F, decltype(std::move(operator*()))>>;
- for overloads (1-2),
- otherwise (
Tis possibly cv-qualifiedvoid),std::remove_cv_t<std::invoke_result_t<F>>.
U must be a valid value type for std::expected. A variable of type U must be constructible from the result of invocation (but does not need to be move-constructible). The return type is std::expected<U, E>.
std::is_constructible_v<E, decltype(error())> is true.std::is_constructible_v<E, decltype(std::move(error()))> is true.Formally, these functions perform the following steps:
- If
*thiscontains an expected valueval:
- Invoke
fas if bystd::invoke(std::forward<F>(f), val)for overloads (1,2) ifstd::is_void_v<T>isfalse;std::invoke(std::forward<F>(f), std::move(val))for overloads (3,4) ifstd::is_void_v<T>isfalse;std::invoke(std::forward<F>(f))ifstd::is_void_v<T>istrue.
- Then:
- if
std::is_void_v<U>isfalse, returns astd::expectedobject that contains an expected value, direct-initialized from the result of invocation; - otherwise, returns
std::expected<U, E>().
- if
- Invoke
- Otherwise (
*thiscontains an error value), returnsstd::expected<U, E>(std::unexpect, error()).
Parameters
| f | - | a suitable function or Callable object whose call signature returns a non-reference type |
Return value
A std::expected object containing either the result of f or an error value, as described above.
Example
| This section is incomplete Reason: no example |
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 3938 | C++23 | the expected value was obtained by value(), which requires E to be copy constructible
|
changed to **this
|
| LWG 3973 | C++23 | the expected value was obtained by **this, which can involve argument-dependent lookup
|
changed to name the member directly |
