From e33347af7259203ab3b109ec4b617d618d1d19fe Mon Sep 17 00:00:00 2001 From: beanljun Date: Mon, 29 Jul 2024 20:59:43 +0800 Subject: [PATCH] =?UTF-8?q?util.h=E6=96=87=E4=BB=B6=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=87=BD=E6=95=B0format=20#67?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/common/include/util.h | 33 ++++++++++++++++++++++++++++----- src/common/util.cpp | 18 ++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/common/include/util.h b/src/common/include/util.h index 9903159..681e303 100644 --- a/src/common/include/util.h +++ b/src/common/include/util.h @@ -16,6 +16,10 @@ #include #include #include +#include +#include +#include +#include #include "config.h" template @@ -42,12 +46,31 @@ void DPrintf(const char* format, ...); void myAssert(bool condition, std::string message = "Assertion failed!"); +// 替换占位符函数 +void replacePlaceholders(std::ostringstream &oss, const std::string &format_str, const std::vector &args); + +// 添加参数到向量中,这里可以对特定类型进行具体处理 +template +void addArg(std::vector &args, const T &value) { + std::ostringstream oss; + + if constexpr (std::is_same_v || std::is_same_v) + oss << std::fixed << std::setprecision(4) << value; // 处理浮点数,保留四位小数 + else if constexpr (std::is_same_v) + oss << std::boolalpha << value; // 处理布尔类型,输出 true 或 false + else + oss << value; + args.push_back(oss.str()); // 将参数添加到向量中 +} + +// 格式化函数,接收可变参数 template -std::string format(const char* format_str, Args... args) { - std::stringstream ss; - int _[] = {((ss << args), 0)...}; - (void)_; - return ss.str(); +std::string format(const std::string &format_str, Args... args) { + std::vector arguments; + (addArg(arguments, args), ...); // 将所有参数转换为字符串并添加到向量中 + std::ostringstream oss; + replacePlaceholders(oss, format_str, arguments); // 替换占位符 + return oss.str(); // 返回格式化后的字符串 } std::chrono::_V2::system_clock::time_point now(); diff --git a/src/common/util.cpp b/src/common/util.cpp index 36ca38f..faadb49 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -66,3 +66,21 @@ void DPrintf(const char *format, ...) { va_end(args); } } + +void replacePlaceholders(std::ostringstream &oss, const std::string &format_str, const std::vector &args) { + size_t arg_index = 0; // 参数索引 + for (size_t i = 0; i < format_str.size(); ++i) { // 遍历格式化字符串 + if (format_str[i] == '%' && arg_index < args.size()) { // 如果遇到占位符 + char specifier = format_str[i + 1]; // 获取类型说明符 + if (specifier == 'd' || specifier == 's' || specifier == 'f' || + specifier == 'c' || specifier == 'x' || specifier == 'b') { + oss << args[arg_index++]; // 替换占位符 + ++i; // 跳过类型说明符 + } else { + oss << format_str[i]; // 处理非占位符字符 + } + } else { + oss << format_str[i]; // 处理非占位符字符 + } + } +}