Namespaces
Variants

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

From cppreference.net
Utilities library
主模板
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 - 一个合适的函数或 可调用对象 ,其返回值为 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 可能触发 实参依赖查找

参见

若当前 expected 包含期望值则返回其本身;否则返回包含转换后非期望值的 expected
(公开成员函数)