Namespaces
Variants

std::optional<T>::或_否则

来自 zh.cppreference.net
 
 
 
 
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

参见

若存在被容纳的值则返回之,否则返回另一值
(公开成员函数)
(C++23)
若存在被容纳的值则返回给定函数在其上的结果,否则返回空的 optional
(公开成员函数)
(C++23)
返回含有被转换的被容纳值的 optional (若其存在),否则返回空的 optional
(公开成员函数)