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() 와 다름). 그렇지 않으면 프로그램은 ill-formed입니다.

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)
                // 정수를 정수 + 1로 매핑
                .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

참고 항목

사용 가능한 경우 포함된 값을 반환하고, 그렇지 않으면 다른 값을 반환합니다
(public member function)
(C++23)
변환된 포함된 값이 존재하는 경우 이를 포함하는 optional 을 반환하고, 그렇지 않으면 빈 optional 을 반환합니다
(public member function)
(C++23)
값이 포함된 경우 optional 자체를 반환하고, 그렇지 않으면 주어진 함수의 결과를 반환합니다
(public member function)