std::expected<T,E>::transform_error

来自cppreference.com
< cpp‎ | utility‎ | expected
2024年3月21日 (四) 05:54Lynnboy讨论 | 贡献的版本

 
 
 
 
template< class F >
constexpr auto transform_error( F&& f ) &;
(1) (C++23 起)
template< class F >
constexpr auto transform_error( F&& f ) const&;
(2) (C++23 起)
template< class F >
constexpr auto transform_error( F&& f ) &&;
(3) (C++23 起)
template< class F >
constexpr auto transform_error( F&& f ) const&&;
(4) (C++23 起)

如果 *this 包含错误值,则以 error() 为实参调用 f 并返回一个包含了它的结果的 std::expected 对象;否则,返回一个包含了 *this 包含的预期值(通过 operator* 获取)的副本的 std::expected 对象。

1,2) 给定类型 Gstd::remove_cv_t<std::invoke_result_t<F, decltype(error())>>
如果 G 不是 std::unexpected 的合法模板实参,或者 G g(std::invoke(std::forward<F>(f), error())); 非良构,那么程序非良构。
效果等价于
if (has_value())
{
    if (std::is_void_v<T>)
        return std::expected<T, G>();
    else
        return std::expected<T, G>(std::in_place, **this);
}
else
    // 返回的 std::expected 对象包含一个以
    // std::invoke(std::forward<F>(f), error())
    // 直接非列表初始化的非预期值
    return /* 一个 std::expected<T, G> 对象 */;
这些重载只有在 std::is_void_v<T>std::is_constructible_v<T, decltype(**this)>true 时才会参与重载决议。
3,4) 给定类型 Gstd::remove_cv_t<std::invoke_result_t<F, decltype(std::move(error()))>>
如果 G 不是 std::unexpected 的合法模板实参,或者 G g(std::invoke(std::forward<F>(f), std::move(error()))); 非良构,那么程序非良构。
效果等价于
if (has_value())
{
    if (std::is_void_v<T>)
        return