命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 工具库‎ | expected
 
 
 
 
主模板
template< class F >
constexpr auto or_else( F&& f ) &;
(1) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&;
(2) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) &&;
(3) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&&;
(4) (C++23 起)
void 偏特化
template< class F >
constexpr auto or_else( F&& f ) &;
(5) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&;
(6) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) &&;
(7) (C++23 起)
template< class F >
constexpr auto or_else( F&& f ) const&&;
(8) (C++23 起)

如果 *this 包含意外值,则以 *this 的意外值作为参数调用 f 并返回其结果。否则,返回表示期望值的 std::expected 对象。

1-4) 期望值用 *this 的期望值 val 初始化。

给定类型 G

1,2) std::remove_cvref_t<std::invoke_result_t<F, decltype(error())>>
3,4) std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(error()))>>
5,6) std::remove_cvref_t<std::invoke_result_t<F, decltype(error())>>
7,8) std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(error()))>>

如果 G 不是 std::expected 的特化,或 std::is_same_v<G::value_type, T>false,则程序格式错误。

1,2) 这些重载仅在 std::is_constructible_v<T, decltype((val))>true 时参与重载决议。
3,4) 这些重载仅在 std::is_constructible_v<T, decltype(std::move(val))>true 时参与重载决议。

目录

[编辑] 参数

f - 一个合适的函数或 Callable 对象,它返回一个 std::expected

[编辑] 返回值

 重载  has_value() 的值
true false
(1,2) G(std::in_place, val) std::invoke(std::forward<F>(f), error())
(3,4) G(std::in_place, std::move(val)) std::invoke(std::forward<F>(f), std::move(error()))
(5,6) G() std::invoke(std::forward<F>(f), error())
(7,8) std::invoke(std::forward<F>(f), std::move(error()))

[编辑] 注解

特性测试 标准 特性
__cpp_lib_expected 202211L (C++23) std::expected 的单子函数

[编辑] 示例

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 3938 C++23 期望值是通过 value()[1] 获得的 改为 **this
LWG 3973 C++23 期望值是通过 **this[2] 获得的 改为 val
  1. value() 要求 E 是可复制构造的(参见 LWG issue 3843),而 operator* 不需要。
  2. **this 可以触发 argument-dependent lookup

[编辑] 另见

如果 expected 包含预期值,返回 expected 自身;否则返回包含转换后的非预期值的 expected
(公共成员函数) [编辑]