命名空间
变体
操作

std::to_chars_result

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

std::to_chars_resultstd::to_chars 的返回类型。它没有基类,只包含以下成员。

目录

[编辑] 数据成员

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

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

operator==(std::to_chars_result)

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

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

此函数对普通非限定查找限定查找不可见,只有当 std::to_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 <array>
#include <charconv>
#include <iostream>
#include <string_view>
#include <system_error>
 
void show_to_chars(auto... format_args)
{
    std::array<char, 10> str;
 
#if __cpp_lib_to_chars >= 202306L and __cpp_structured_bindings >= 202406L
    // use C++26 structured bindings declaration as condition (P0963)
    // and C++26 to_chars_result::operator bool() for error checking (P2497)
    if (auto [ptr, ec] =
            std::to_chars(str.data(), str.data() + str.size(), format_args...))
        std::cout << std::string_view(str.data(), ptr) << '\n';
    else
        std::cout << std::make_error_code(ec).message() << '\n';
#elif __cpp_lib_to_chars >= 202306L
    // use C++26 to_chars_result::operator bool() for error checking (P2497)
    if (auto result =
            std::to_chars(str.data(), str.data() + str.size(), format_args...))
        std::cout << std::string_view(str.data(), result.ptr) << '\n';
    else
        std::cout << std::make_error_code(result.ec).message() << '\n';
#else
    // fallback to C++17 if-with-initializer and structured bindings
    if (auto [ptr, ec] =
            std::to_chars(str.data(), str.data() + str.size(), format_args...);
        ec == std::errc())
        std::cout << std::string_view(str.data(), ptr - str.data()) << '\n';
    else
        std::cout << std::make_error_code(ec).message() << '\n';
#endif
}
 
int main()
{
    show_to_chars(42);
    show_to_chars(+3.14159F);
    show_to_chars(-3.14159, std::chars_format::fixed);
    show_to_chars(-3.14159, std::chars_format::scientific, 3);
    show_to_chars(3.1415926535, std::chars_format::fixed, 10);
}

可能的输出

42
3.14159
-3.14159
-3.142e+00
Value too large for defined data type

[编辑] 参阅

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