std::optional<T>::or_else

来自cppreference.com
< cpp‎ | utility‎ | optional
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
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 - 返回 std::optional<T> 的函数或可调用 (Callable) 对象

返回值

*thisf 的结果,如上所述。

注解

功能特性测试 标准 功能特性
__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 << "无值: ";
        return maybe_int{0};
    };
 
    maybe_int x;
    std::cout << x.or_else(valueless).value() << '\n';
 
    x = 42;
    std::cout << "有值: ";
    std::cout << x.or_else(valueless).value() << '\n';
 
    x.reset();
    std::cout << x.or_else(valueless).value() << '\n';
}

输出:

无值: 0
有值: 42
无值: 0

参阅

在所含值可用时返回它,否则返回另一个值
(公开成员函数)
(C++23)
在所含值存在时返回对其应用给定的函数的结果,否则返回空的 optional
(公开成员函数)
(C++23)
在所含值存在时返回含有变换后的所含值的 optional,否则返回空的 optional
(公开成员函数)