设计一个能够灵活存储各种类型和数量参数的日志系统

1. 数据结构设计

我们需要一个能够容纳不同类型参数的容器。可以通过以下方式实现:

  • 使用一个 std::variantstd::any 类型来存储不同类型的参数值。
  • 使用 std::mapstd::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
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值