C++ 格式化字符串傳統方案各有缺陷:
sprintf:類型不安全、緩衝區溢出風險、不支援用戶定義類型。stringstream:類型安全但效率低、語法冗長。boost::format:功能強但編譯慢、體積大、效率一般。fastformat:過於龐大、集成困難。CPPFormatLibrary (FL) 旨在提供 .NET 風格格式化語法、編譯期類型安全、Header-Only、零開銷抽象 的現代化方案。
"{0}, {1:X}, {2,-10:F2}"(索引、對齊、格式規範)。std::string/wstring、char*、自定義類型(特化 FormatValue)。#include "Format.hpp"
using namespace FormatLibrary;
std::string s;
StandardLibrary::FormatTo(s, "{0}--#{1,8}--#{2}", 100, -40.2f, "String");
// s == "100--# -40.20--#String"
std::wstring ws;
StandardLibrary::FormatTo(ws, L"Test{1}, {2:F4}, {0}, {0,4}", L" X ", 20, -10.005f);
// ws == L"Test20, -10.0050, X , X"
Windows VS2013 Release / Mac Xcode Release 下 10 萬次格式化:
FL : ~0.076s (Win) / ~0.090s (Mac) sprintf : ~0.270s (Win) / ~0.193s (Mac)
FL 不僅類型安全,速度還超越 sprintf。
Format.hpp,無庫文件。FString)可通過特化 FormatAdapter 接入,僅需數十行代碼。CPPFormatLibrary 以現代 C++ 技術重新定義格式化體驗:.NET 風格語法直觀強大,編譯期類型安全消除整類運行時錯誤,Header-Only 部署零摩擦,性能領先傳統方案。歡迎在項目中替代 sprintf/stringstream。