1. 数据结构设计
我们需要一个能够容纳不同类型参数的容器。可以通过以下方式实现:
- 使用一个
std::variant
或std::any
类型来存储不同类型的参数值。 - 使用
std::map
或std::unordered_map
来存储参数的键值对。 - 每条日志是一组参数,可以使用一个类或结构体封装。
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <variant>
#include <sstream>
// 定义支持的参数类型
using ParamValue = std::variant<int, double, std::string>;
// 日志条目类
class LogEntry {
public:
void addParam(const std::string& name, ParamValue value) {
params[name] = value;
}
std::string toString() const {
std::ostringstream oss;
oss << "Log Entry: \n";
for (const auto& [key, value] : params) {
oss << " " << key << ": " << formatValue(value) << "\n";
}
return oss.str();
}
private:
std::map<std::string, ParamValue> params;
// 格式化输出
std::string formatValue(const ParamValue& value) const {
return std::visit([](auto&& arg) -> std::string {
std::ostringstream oss;
oss << arg;
return oss.str();
}, value);
}
};
2. 使用示例
// 日志存储器
class Logger {
public:
void addLog(const LogEntry& entry) {
logs.push_back(entry);
}
void printLogs() const {
for (const auto& log : logs) {
std::cout << log.toString() << std::endl;
}
}
private:
std::vector<LogEntry> logs;
};
3. 输出示例
Log Entry:
Width: 100
Height: 200
Area: 20000.5
Log Entry:
Angle: 45
Description: Sample Log