gpt4 book ai didi

c++ - 为 Boost 日志对象重载 << 运算符

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:09 25 4
gpt4 key购买 nike

所以我想将 Boost.Log 用于我所有的日志记录目的。我目前编写了一个类,其中包含实例化和设置辅助方法所需的所有操作。

问题是我想重载 << 运算符以 cout 方式使用它。我希望能够使用它,因为具有不同的参数类型似乎是最大的问题。

这是我尝试过的:

template <typename T>
void trace::operator <<(T data)
{
std::string text=boost::lexical_cast<std::string>(data);
std::cout<<data<<std::endl;
BOOST_LOG_TRIVIAL(debug) << text;
}

但是,我知道这在逻辑上有点缺陷。为了能够将多个参数传递给 << 它需要递归。但是我有点困惑如何使用 boost log 来做到这一点。

我是否必须使用自定义接收器而不是方便的 boost 宏来定义日志系统?如果是这样,这是否支持 std::ostream 返回?我猜这将是流中的返回值和输入值。

最佳答案

如果我正确理解您的问题,您需要使用 << 运算符记录有关您的对象的信息。Boost Log 使用 ostream 兼容的运算符,所以你只需要为你的类定义 << 运算符:

class your_class_t{
public:
std::string m_data;
int m_value;

friend std::ostream& operator<< (std::ostream& oss, your_class_t const & val) {
oss<<val.m_data << ": " << val.m_value;
return oss;
}
}

然后你可以在ostream中推送你的类:

your_class_t mytest;
mytest.m_data = "hi";
mytest.m_value = 123;
BOOST_LOG_TRIVIAL(debug) << mytest;

你会得到 hi: 123

关于c++ - 为 Boost 日志对象重载 << 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17269499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com