std::optional<T>::and_then
来自cppreference.com
| |
(1) | (C++23 起) |
| |
(2) | (C++23 起) |
| |
(3) | (C++23 起) |
| |
(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}; })
// 拉平映射 string 为 int (失败时产生空的 optional)
.and_then(to_int)
// 映射 int 为 int + 1
.transform([](int n) { return n + 1; })
// 转换回 string
.transform([](int n) { return std::to_string(n); })
// 以 and_then 替换,并用 "NaN" 变换并忽略所有剩余的空 optional
// and_then and ignored by transforms with "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
