std::optional<T>::or_else
cppreference.net에서
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) |