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

来自cppreference.com
< cpp‎ | utility‎ | expected
 
 
 
 
主模板
template<class F >
constexprauto or_else( F&& f )&;
(1) (C++23 起)
template<class F >
constexprauto or_else( F&& f )const&;
(2) (C++23 起)
template<class F >
constexprauto or_else( F&& f )&&;
(3) (C++23 起)
template<class F >
constexprauto or_else( F&& f )const&&;
(4) (C++23 起)
void 部分特化
template<class F >
constexprauto or_else( F&& f )&;
(5) (C++23 起)
template<class F >
constexprauto or_else( F&& f )const&;
(6) (C++23 起)
template<class F >
constexprauto or_else( F&& f )&&;
(7) (C++23 起)
template<class F >
constexprauto 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() 的值
truefalse
(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_expected202211L(C++23)std::expected 的单子式函数

[编辑]示例

[编辑]缺陷报告

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

缺陷报告 应用于 出版时的行为 正确行为
LWG 3938 C++23 通过 value() 获取预期值[1] 改成 **this
LWG 3973 C++23 通过 **this 获取预期值[2] 改成 val
  1. value() 要求 E 可复制构造(见 LWG 问题 3843),而 operator* 不要求。
  2. **this 会触发实参依赖查找

[编辑]参阅

若含有预期值则返回 expected 本身,否则返回含有变换后非预期值的 expected
(公开成员函数)[编辑]
close