std::optional<T>:: and_then
From cppreference.net
|
template
<
class
F
>
constexpr auto and_then ( F && f ) & ; |
(1) | (自 C++23 起) |
|
template
<
class
F
>
constexpr auto and_then ( F && f ) const & ; |
(2) | (自 C++23 起) |
|
template
<
class
F
>
constexpr auto and_then ( F && f ) && ; |
(3) | (自 C++23 起) |
|
template
<
class
F
>
constexpr auto and_then ( F && f ) const && ; |
(4) | (自 C++23 起) |
若
*
this
包含值,则以所含值作为参数调用
f
,并返回该调用的结果;否则返回空的
std::optional
。
返回类型(见下文)必须是
std::optional
的特化(与
transform()
不同)。否则程序将是非良构的。
1)
等价于
if (*this) return std::invoke(std::forward<F>(f), value()); else return std::remove_cvref_t<std::invoke_result_t<F, T&>>{};
2)
等价于
if (*this) return std::invoke(std::forward<F>(f), value()); else return std::remove_cvref_t<std::invoke_result_t<F, const T&>>{};
3)
等价于
if (*this) return std::invoke(std::forward<F>(f), std::move(value())); else return std::remove_cvref_t<std::invoke_result_t<F, T>>{};
4)
等价于
if (*this) return std::invoke(std::forward<F>(f), std::move(value()); else return std::remove_cvref_t<std::invoke_result_t<F, const T>>{};
目录 |
参数
| f | - | 一个合适的函数或 Callable 对象,其返回值为 std::optional |
返回值
f 的结果或一个空的 std::optional ,如上所述。
注释
某些语言将此操作称为 flatmap 。
| 功能测试 宏 | 值 | 标准 | 特性 |
|---|---|---|---|
__cpp_lib_optional
|
202110L
|
(C++23) | std::optional 中的单子操作 |
示例
运行此代码
#include <charconv> #include <iomanip> #include <iostream> #include <optional> #include <ranges> #include <string> #include <string_view> #include <vector> std::optional<int> to_int(std::string_view sv) { int r{}; auto [ptr, ec]{std::from_chars(sv.data(), sv.data() + sv.size(), r)}; if (ec == std::errc()) return r; else return std::nullopt; } int main() { using namespace std::literals; const std::vector<std::optional<std::string>> v { "1234", "15 foo", "bar", "42", "5000000000", " 5", std::nullopt, "-43" }; for (auto&& x : v | std::views::transform( [](auto&& o) { // 调试输出输入 optional<string> 的内容 std::cout << std::left << std::setw(13) << std::quoted(o.value_or("nullopt")) << " -> "; return o // 如果 optional 为 nullopt,则将其转换为包含空字符串的 optional .or_else([]{ return std::optional{""s}; }) // 从字符串到整数的平面映射(在转换失败处生成空 optional) .and_then(to_int) // 将整数映射为整数加一 .transform([](int n) { return n + 1; }) // 转换回字符串 .transform([](int n) { return std::to_string(n); }) // 将所有由 and_then 产生并被 transform 忽略的空 optional 替换为 "NaN" .value_or("NaN"s); })) std::cout << x << '\n'; }
输出:
"1234" -> 1235 "15 foo" -> 16 "bar" -> NaN "42" -> 43 "5000000000" -> NaN " 5" -> NaN "nullopt" -> NaN "-43" -> -42
参见
|
若存在被容纳值则返回之,否则返回另一值
(公开成员函数) |
|
|
(C++23)
|
若存在被容纳值则返回含变换后值的
optional
,否则返回空
optional
(公开成员函数) |
|
(C++23)
|
若
optional
含值则返回其本身,否则返回给定函数的结果
(公开成员函数) |