命名空间
变体
操作

std::from_chars_result

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

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

内容

[编辑] 数据成员

成员名 定义
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{}

[编辑] 注解

特性测试 Std 特性
__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.

[编辑] 参见

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