std::from_chars_result
來自 cppreference.com
定義於標頭檔案 <charconv> |
||
struct from_chars_result; |
(C++17 起) | |
std::from_chars_result
是 std::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== 比較 ptr
和 ec
)比較兩個引數。
此函式對於普通的 非限定查詢 或 限定查詢 不可見,並且只有當 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.
[編輯] 參見
(C++17) |
將字元序列轉換為整數或浮點值 (函式) |