Namespaces
Variants

std::optional<T>:: or_else

From cppreference.net
Utilities library
template < class F >
constexpr optional or_else ( F && f ) const & ;
(1) (C++23 이후)
template < class F >
constexpr optional or_else ( F && f ) && ;
(2) (C++23 이후)

값이 포함되어 있으면 * this 를 반환합니다. 그렇지 않으면 f 의 결과를 반환합니다.

프로그램은 std:: remove_cvref_t < std:: invoke_result_t < F >> std:: optional < T > 와 동일하지 않을 경우 형식이 잘못되었습니다.

1) return * this ? * this : std:: forward < F > ( f ) ( ) ; 와 동등합니다. 이 오버로드는 std:: copy_constructible < T > std:: invocable < F > 가 모두 충족될 때만 오버로드 해결에 참여합니다.
2) 다음과 동일함: return * this ? std :: move ( * this ) : std:: forward < F > ( f ) ( ) ; . 이 오버로드는 std:: move_constructible < T > std:: invocable < F > 가 모두 충족될 때만 오버로드 해결에 참여합니다.

목차

매개변수

f - Callable 요구 사항을 만족하는 함수 또는 객체로서 std:: optional < T > 를 반환함

반환값

* this 또는 위에서 설명한 f 의 결과입니다.

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_optional 202110L (C++23) 모나딕 연산 in std::optional

예제

#include <iostream>
#include <optional>
#include <string>
int main()
{
    using maybe_int = std::optional<int>;
    auto valueless = []
    {
        std::cout << "Valueless: ";
        return maybe_int{0};
    };
    maybe_int x;
    std::cout << x.or_else(valueless).value() << '\n';
    x = 42;
    std::cout << "Has value: ";
    std::cout << x.or_else(valueless).value() << '\n';
    x.reset();
    std::cout << x.or_else(valueless).value() << '\n';
}

출력:

Valueless: 0
Has value: 42
Valueless: 0

참고 항목

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