Namespaces
Variants

std::optional<T>:: and_then

From cppreference.net
Utilities library
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) モナド操作 in 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)
                // intをint + 1にマップ
                .transform([](int n) { return n + 1; })
                // 文字列に戻す
                .transform([](int n) { return std::to_string(n); })
                // and_thenで残され、transformsで無視されたすべての空の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 自体を返し、それ以外の場合は指定された関数の結果を返す
(公開メンバ関数)