名前空間
変種
操作

std::optional<T>::and_then

From 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で非推奨)
 
 
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 - std::optional を返す適切な関数またはCallable オブジェクト

[編集] 戻り値

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 自身を返し、そうでなければ与えられた関数の結果を返す
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)