命名空间
变体
操作

std::optional<T>::or_else

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
template< class F >
constexpr optional or_else( F&& f ) const&;
(1) (since C++23)
template< class F >
constexpr optional or_else( F&& f ) &&;
(2) (since 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 - 一个返回 std::optional<T> 的函数或 Callable 对象

[编辑] 返回值

如上所述的 *thisf 的结果。

[编辑] 说明

特性测试 Std 特性
__cpp_lib_optional 202110L (C++23) std::optional 中的 Monadic 操作

[编辑] 示例

#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
(公共成员函数) [编辑]