Namespaces
Variants

std::optional<T>::and_then

cppreference.net에서 발췌
 
 
유틸리티 라이브러리
일반 유틸리티
관계 연산자 (C++20부터 폐지됨)
정수 비교 함수
(C++20)(C++20)(C++20)    
(C++20)
Swap 및 타입 연산
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
공통 어휘 타입
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
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)