命名空间
变体
操作

std::from_chars_result

来自 cppreference.cn
< cpp‎ | 工具
定义于头文件 <charconv>
struct from_chars_result;
(C++17 起)

std::from_chars_resultstd::from_chars 的返回类型。它没有基类,并且只包含以下成员。

目录

[编辑] 数据成员

成员名称 (Member name) 定义
ptr
类型为 const char* 的指针
(公有成员对象)
ec
类型为 std::errc 的错误码
(公有成员对象)

[编辑] 成员函数和友元函数

operator==(std::from_chars_result)

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

使用 默认比较(它分别使用 operator== 比较 ptrec)比较两个参数。

此函数对于普通的 非限定查找限定查找 不可见,并且只有当 std::from_chars_result 是参数的关联类时,才能通过 实参依赖查找 找到。

!= 运算符由 operator== 合成

operator bool

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

检查转换是否成功。返回 ec == std::errc{}

[编辑] 注意

特性测试 标准 特性
__cpp_lib_to_chars 201611L (C++17) 基本字符串转换(std::to_chars, std::from_chars
202306L (C++26) 测试<charconv>函数的成功或失败

[编辑] 示例

#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
}

输出

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.

[编辑] 参见

将字符序列转换为整数或浮点值
(函数) [编辑]