Namespaces
Variants

std:: expected

From cppreference.net
Utilities library
헤더 파일에 정의됨 <expected>
template < class T, class E >
class expected ;
(1) (C++23부터)
template < class T, class E >

requires std:: is_void_v < T >

class expected < T, E > ;
(2) (C++23부터)

클래스 템플릿 std::expected 는 두 가지 값 중 하나를 표현하는 방법을 제공합니다: T 타입의 expected 값, 혹은 E 타입의 unexpected 값. expected 는 절대 값이 없지 않습니다.

1) 주 템플릿. 자체 저장소 내에 예상된 값 또는 예상치 못한 값을 포함하며, 이 저장소는 내부에 중첩되어 expected 객체 내에 위치합니다.
2) The void partial specialization. Represents an expected void value or contains an unexpected value. If it contains an unexpected value, it is nested within the expected object.

프로그램이 참조 타입, 함수 타입, 또는 std::unexpected 의 특수화를 사용하여 expected 를 인스턴스화하는 경우, 그 프로그램은 형식이 잘못되었습니다. 또한, T std::in_place_t 또는 std::unexpect_t 이어서는 안 됩니다.

목차

템플릿 매개변수

T - 기대값의 타입. 해당 타입은 (cv 한정자가 있을 수 있는) void 이거나 Destructible 요구 사항을 충족해야 합니다 (특히, 배열 및 참조 타입은 허용되지 않음).
E - 예상치 못한 값의 타입. 해당 타입은 Destructible 요구 사항을 충족해야 하며, std::unexpected 에 대한 유효한 템플릿 인수여야 합니다 (특히, 배열, 비객체 타입 및 cv 한정 타입은 허용되지 않음).

중첩 타입

유형 정의
value_type T
error_type E
unexpected_type std::unexpected<E>

멤버 템플릿

템플릿 정의
rebind < U > std :: expected < U, error_type >

데이터 멤버

멤버 설명
bool has_val 현재 expected 객체가 기대값을 나타내는지 여부
( 설명 전용 멤버 객체* )
T val (메인 템플릿 전용) 기대값
( 설명 전용 variant 멤버 객체* )
E unex 예상치 못한 값
( 설명 전용 variant 멤버 객체* )

멤버 함수

expected 객체를 생성합니다
(public member function)
expected 객체와 포함된 값을 파괴합니다
(public member function)
내용을 할당합니다
(public member function)
Observers
기대값에 접근합니다
(public member function)
객체가 기대값을 포함하는지 확인합니다
(public member function)
기대값을 반환합니다
(public member function)
예상치 못한 값을 반환합니다
(public member function)
기대값이 존재하면 반환하고, 그렇지 않으면 다른 값을 반환합니다
(public member function)
예상치 못한 값이 존재하면 반환하고, 그렇지 않으면 다른 값을 반환합니다
(public member function)
Monadic operations
기대값이 존재하면 주어진 함수의 결과를 반환하고, 그렇지 않으면 expected 자체를 반환합니다
(public member function)
기대값이 존재하면 변환된 기대값을 포함하는 expected 를 반환하고, 그렇지 않으면 expected 자체를 반환합니다
(public member function)
기대값을 포함하면 expected 자체를 반환하고, 그렇지 않으면 예상치 못한 값에 대한 주어진 함수의 결과를 반환합니다
(public member function)
기대값을 포함하면 expected 자체를 반환하고, 그렇지 않으면 변환된 예상치 못한 값을 포함하는 expected 를 반환합니다
(public member function)
Modifiers
제자리에서 기대값을 생성합니다
(public member function)
내용을 교환합니다
(public member function)

비멤버 함수

(C++23)
expected 객체 비교
(함수 템플릿)
std::swap 알고리즘 전문화
(함수)

헬퍼 클래스

(C++23)
예상치 못한 값으로 표현됨
(클래스 템플릿)
예상치 못한 값을 포함하는 expected 에 대한 검증된 접근을 나타내는 예외
(클래스 템플릿)
expected 에서 예상치 못한 값에 대한 인플레이스 생성 태그
(태그)

참고 사항

동일한 기능을 가진 타입들은 Rust에서는 Result 라고 부르고, Haskell에서는 Either 라고 부릅니다.

기능 테스트 매크로 표준 기능
__cpp_lib_expected 202202L (C++23) 클래스 템플릿 std::expected 및 관련 헬퍼 클래스들
202211L (C++23) std::expected 모나딕 함수들

예제

#include <cmath>
#include <expected>
#include <iomanip>
#include <iostream>
#include <string_view>
enum class parse_error
{
    invalid_input,
    overflow
};
auto parse_number(std::string_view& str) -> std::expected<double, parse_error>
{
    const char* begin = str.data();
    char* end;
    double retval = std::strtod(begin, &end);
    if (begin == end)
        return std::unexpected(parse_error::invalid_input);
    else if (std::isinf(retval))
        return std::unexpected(parse_error::overflow);
    str.remove_prefix(end - begin);
    return retval;
}
int main()
{
    auto process = [](std::string_view str)
    {
        std::cout << "str: " << std::quoted(str) << ", ";
        if (const auto num = parse_number(str); num.has_value())
            std::cout << "value: " << *num << '\n';
            // num에 값이 없는 경우, num을 역참조하면
            // 정의되지 않은 동작이 발생하고,
            // num.value()는 std::bad_expected_access를 던집니다.
            // num.value_or(123)은 지정된 기본값 123을 사용합니다.
        else if (num.error() == parse_error::invalid_input)
            std::cout << "error: invalid input\n";
        else if (num.error() == parse_error::overflow)
            std::cout << "error: overflow\n";
        else
            std::cout << "unexpected!\n"; // 또는 std::unreachable() 호출
    };
    for (auto src : {"42", "42abc", "meow", "inf"})
        process(src);
}

출력:

str: "42", value: 42
str: "42abc", value: 42
str: "meow", error: invalid input
str: "inf", error: overflow

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 4141 C++23 저장소 할당 요구사항이
혼란스러웠음
포함된 객체는 반드시
expected 객체 내에
중첩되어야 함

참고문헌

  • C++23 표준 (ISO/IEC 14882:2024):
  • 22.8 Expected 객체 [expected]

참고 항목

(C++17)
타입 안전 식별 공용체
(클래스 템플릿)
(C++17)
객체를 보유할 수도 있고 보유하지 않을 수도 있는 래퍼
(클래스 템플릿)