命名空間
變體
動作

std::to_chars_result

出自 cppreference.com
< cpp‎ | 工具
定義於標頭檔 <charconv>
struct to_chars_result;
(自 C++17 起)

std::to_chars_resultstd::to_chars 的回傳型別。它沒有基底類別,且僅包含下列成員。

目錄

[編輯] 資料成員

成員名稱 定義
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)。

此函數對一般非限定名稱查詢 (unqualified lookup)限定名稱查詢 (qualified lookup) 不可見,且僅能透過引數依賴查詢 (argument-dependent lookup) 找到,前提是 std::to_chars_result 為該引數的相關類別。

!= 運算子是從 operator== 合成 (synthesized) 的。

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)
將整數或浮點數值轉換為字元序列
(函式) [編輯]
English Deutsch 日本語 中文(简体) 中文(繁體)