Namespaces
Variants

std::optional<T>:: or_else

From cppreference.net
Utilities library
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
(公开成员函数)