utility_from_chars_result

utility_from_chars_result (문자열 변환 결과 타입)

이 페이지는 std::from_chars_result 타입에 대해 설명해요. std::from_chars 함수의 반환 타입으로, 변환 성공 여부와 처리된 위치를 함께 알려주는 구조체예요. 기본 클래스가 없고, 아래에 나열된 멤버만 가지고 있어요.

출처: cppreference

본문

데이터 멤버

멤버 이름 정의
ptr const char* 타입의 포인터 (공개 멤버 객체)
ec std::errc 타입의 오류 코드 (공개 멤버 객체)

멤버 및 friend 함수

operator== (std::from_chars_result)

friend bool operator==(const from_chars_result&, const from_chars_result&) = default; (since C++20)

두 인자를 기본 비교 방식으로 비교해요. 이때 ptrec를 각각 operator==로 비교한답니다.

이 함수는 일반적인 비한정 또는 한정 조회로는 보이지 않아요. 오직 인자 연관 조회(argument-dependent lookup)를 통해서만 찾을 수 있으며, std::from_chars_result가 인자의 연관 클래스일 때 사용할 수 있어요.

!= 연산자는 operator==로부터 합성돼요.

operator bool

constexpr explicit operator bool() const noexcept; (since C++26)

변환이 성공했는지 확인해요. ec == std::errc{}와 같은 값을 반환해요.

Notes

Feature-test macro Value Std Feature
__cpp_lib_to_chars 201611L (C++17) 기본 문자열 변환 (std::to_chars, std::from_chars)
202306L (C++26) <charconv> 함수의 성공/실패 여부 테스트

Example

#include <cassert>
#include <charconv>
#include <iomanip>
#include <iostream>
#include <optional>
#include <string_view>
#include <system_error>

int main()
{
    for (std::string_view const str : {"1234", "15 foo", "bar", " 42", "5000000000"})
    {
        std::cout << "String: " << std::quoted(str) << ". ";
        int result{};
        auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);

        if (ec == std::errc())
            std::cout << "Result: " << result << ", ptr -> " << std::quoted(ptr) << '\n';
        else if (ec == std::errc::invalid_argument)
            std::cout << "This is not a number.\n";
        else if (ec == std::errc::result_out_of_range)
            std::cout << "This number is larger than an int.\n";
    }

    // C++23's constexpr from_char demo / C++26's operator bool() demo:
    auto to_int = [](std::string_view s) -> std::optional<int>
    {
        int value{};
#if __cpp_lib_to_chars >= 202306L
        if (std::from_chars(s.data(), s.data() + s.size(), value))
#else
        if (std::from_chars(s.data(), s.data() + s.size(), value).ec == std::errc{})
#endif
            return value;
        else
            return std::nullopt;
    };

    assert(to_int("42") == 42);
    assert(to_int("foo") == std::nullopt);
#if __cpp_lib_constexpr_charconv and __cpp_lib_optional >= 202106
    static_assert(to_int("42") == 42);
    static_assert(to_int("foo") == std::nullopt);
#endif
}

Output:

String: "1234". Result: 1234, ptr -> ""
String: "15 foo". Result: 15, ptr -> " foo"
String: "bar". This is not a number.
String: " 42". This is not a number.
String: "5000000000". This number is larger than an int.

See also

from_chars (C++17) 문자 시퀀스를 정수 또는 부동소수점 값으로 변환해요 (함수) [edit]

더 알아보기 (Learn more)

cppreference