std::optional<T>::or_else
来自 cppreference.cn
template< class F > constexpr optional or_else( F&& f ) const&; |
(1) | (C++23 起) |
template< class F > constexpr optional or_else( F&& f ) &&; |
(2) | (C++23 起) |
如果包含值,则返回 *this。否则,返回 f 的结果。
如果 std::remove_cvref_t<std::invoke_result_t<F>> 与 std::optional<T> 不同,则程序格式错误。
1) 等价于 return *this ? *this : std::forward<F>(f)();。此重载仅在同时建模 std::copy_constructible<T> 和 std::invocable<F> 时参与重载决议。
2) 等价于 return *this ? std::move(*this) : std::forward<F>(f)();。此重载仅在同时建模 std::move_constructible<T> 和 std::invocable<F> 时参与重载决议。
目录 |
[编辑] 参数
f | - | 一个函数或 可调用 (Callable) 对象,它返回一个 std::optional<T> |
[编辑] 返回值
如上所述,返回 *this 或 f 的结果。
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_optional |
202110L |
(C++23) | std::optional 中的单子操作 |
[编辑] 示例
运行此代码
#include <iostream> #include <optional> #include <string> int main() { using maybe_int = std::optional<int>; auto valueless = [] { std::cout << "Valueless: "; return maybe_int{0}; }; maybe_int x; std::cout << x.or_else(valueless).value() << '\n'; x = 42; std::cout << "Has value: "; std::cout << x.or_else(valueless).value() << '\n'; x.reset(); std::cout << x.or_else(valueless).value() << '\n'; }
输出
Valueless: 0 Has value: 42 Valueless: 0
[编辑] 参阅
如果可用,返回包含的值,否则返回另一个值 (public 成员函数) | |
(C++23) |
如果存在包含的值,则返回给定函数对该值的结果,否则返回空的 optional (public 成员函数) |
(C++23) |
如果存在包含的值,则返回一个包含转换后的值的 optional ,否则返回一个空的 optional (public 成员函数) |