C++20 格式化字符串的實現(xiàn)
在 C++20 中引入的 std::format 是一個強大的工具,用于格式化字符串。它提供了一種簡潔、類型安全且靈活的方式來構(gòu)建格式化字符串,同時避免了傳統(tǒng)的格式化函數(shù)帶來的許多問題。
概述
std::format 是 C++20 中引入的一個新功能,用于格式化字符串。它位于 <format> 頭文件中,并提供了一種類似于 Python 中 f-string 的語法來構(gòu)建格式化字符串。
使用場景
字符串格式化
std::string name = "Alice"; int age = 30; std::string formatted_str = std::format("Name: {}, Age: {}", name, age); //output: //Name: Alice, Age: 30
文中使用{}作為占位符來進行文字替換,提出如下三個問題:
1.替換規(guī)則是什么,
2.如果占位符多/或少會出現(xiàn)什么問題呢;
3.如果實際輸出時帶輸出字符串需要被{}包含時如何實現(xiàn)呢。
格式化規(guī)則
_EXPORT_STD template <class... _Types> _NODISCARD string format(const format_string<_Types...> _Fmt, _Types&&... _Args) { return _STD vformat(_Fmt.get(), _STD make_format_args(_Args...)); }
為便于描述,_Fmt后續(xù)稱為——“格式字符串”,_Args后續(xù)稱為——“變量”
變量依次替換“格式字符串”中的{};如上例
std::string name = "Alice"; int age = 30; std::string formatted_str = std::format("Name: {}, Age: {}", name, age); //output:Name: Alice, Age: 30
如果“格式字符串”中的{}數(shù)量大于變量的個數(shù),如下例代碼,編譯成功,但是運行拋出“std::format_error"異常。
std::string formatted_str = std::format("Name: {}, {},Age: {}", "Alice", 30);//throw error
如果“格式字符串”中的{}數(shù)量小于等于變量的個數(shù),假設(shè)變量個數(shù)為n,則n個變量會替換前n個{}。
std::string formatted_str = std::format("Name: {},Age: {}", "Alice", 30); std::string formatted_str = std::format("Name: {}, Age: {}", "Alice", 30,"hello"); //output: //Name: Alice,Age: 30 //Name: Alice, Age: 30
如果帶輸出的變量需要被{}包含,需要使用{{}}包含{}進而對{}轉(zhuǎn)義,形如{{{}}},最內(nèi)測的{}為占位符,而外側(cè)的{{}}是{}的占位符
std::string ret = std::format("name {} age {{ {} }}", "janny", 20); //output: //name janny age { 20 }
自定義類型的格式化
為實現(xiàn)自定義數(shù)據(jù)類型的格式化,需要為其提供格式化器,格式化器是標準的,可以參考如下進行修改即可。
#include <format> #include <iostream> struct vector3 { int x, y,z; }; // 定義一個格式化處理程序 template <> struct std::formatter<vector3> { auto parse(format_parse_context& ctx) { return ctx.end(); } template <typename FormatContext> auto format(const vector3 & p, FormatContext& ctx) const { return std::format_to(ctx.out(), "({}, {}, {})", p.x, p.y,p.z); } }; void using_format() { vector3 p{ 10, 20,30 }; std::cout << std::format("The point is: {}\n", p) << std::endl; } //output //The point is: (10, 20, 30)
總結(jié)
std::format提供類型安全且靈活的字符串格式化方法,使用時要牢記{}的個數(shù)不要大于變量的個數(shù);同時,自定義數(shù)據(jù)類型需要提供格式化器。
到此這篇關(guān)于C++20 格式化字符串的實現(xiàn)的文章就介紹到這了,更多相關(guān)C++20 格式化字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!