名稱空間
變體
操作

std::optional<T>::and_then

來自 cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
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)
        {
            // debug print the content of input optional<string>
            std::cout << std::left << std::setw(13)
                      << std::quoted(o.value_or("nullopt")) << " -> ";
 
            return o
                // if optional is nullopt convert it to optional with "" string
                .or_else([]{ return std::optional{""s}; })
                // flatmap from strings to ints (making empty optionals where it fails)
                .and_then(to_int)
                // map int to int + 1
                .transform([](int n) { return n + 1; })
                // convert back to strings
                .transform([](int n) { return std::to_string(n); })
                // replace all empty optionals that were left by
                // 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

[編輯] 參閱

如果可用,返回包含的值,否則返回另一個值
(public member function) [編輯]
(C++23)
如果存在包含的值,則返回一個包含轉換後的值的 optional,否則返回一個空的 optional
(public member function) [編輯]
(C++23)
如果 optional 包含值,則返回 optional 本身,否則返回給定函式的結果
(public member function) [編輯]