Skip to content

Commit

Permalink
util.h文件中的模板函数format youngyangyang04#67
Browse files Browse the repository at this point in the history
  • Loading branch information
beanljun committed Jul 29, 2024
1 parent 2b79901 commit e33347a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/common/include/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
#include <random>
#include <sstream>
#include <thread>
#include <string>
#include <vector>
#include <iomanip>
#include <type_traits>
#include "config.h"

template <class F>
Expand All @@ -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<std::string> &args);

// 添加参数到向量中,这里可以对特定类型进行具体处理
template <typename T>
void addArg(std::vector<std::string> &args, const T &value) {
std::ostringstream oss;

if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double>)
oss << std::fixed << std::setprecision(4) << value; // 处理浮点数,保留四位小数
else if constexpr (std::is_same_v<T, bool>)
oss << std::boolalpha << value; // 处理布尔类型,输出 true 或 false
else
oss << value;
args.push_back(oss.str()); // 将参数添加到向量中
}

// 格式化函数,接收可变参数
template <typename... Args>
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<std::string> arguments;
(addArg(arguments, args), ...); // 将所有参数转换为字符串并添加到向量中
std::ostringstream oss;
replacePlaceholders(oss, format_str, arguments); // 替换占位符
return oss.str(); // 返回格式化后的字符串
}

std::chrono::_V2::system_clock::time_point now();
Expand Down
18 changes: 18 additions & 0 deletions src/common/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> &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]; // 处理非占位符字符
}
}
}

0 comments on commit e33347a

Please sign in to comment.