如何重载 ostream 运算符<<以使其在 C++ 中与 log4cxx 一起使用?

How to overload the ostream operator << to make it work with log4cxx in C++?

本文关键字:lt 中与 C++ log4cxx 一起 何重载 运算符 ostream 重载      更新时间:2023-10-16

假设我有一个类 A 和一个运算符<<声明如下:

// A.h
class A
{
    // A stuff
};
std::ostream& operator<<(std::ostream& os, const A& a);

在其他地方,我将我的记录器与 A 一起使用:

LoggerPtr logger(LogManager::getLogger("ThisObject"));
A a;
LOG4CXX_INFO(logger, "A: " << a);

编译器抱怨:二进制 '<<' :未找到采用类型为"const A"的右操作数的运算符(或者没有可接受的转换)D:\dev\cpp\lib\apache-log4cxx\log4cxx\include\log4cxx\helpers\messagebuffer.h 190

这个错误将我带到operator<<的声明:

// messagebuffer.h
template<class V>
std::basic_ostream<char>& operator<<(CharMessageBuffer& os, const V& val) {
    return ((std::basic_ostream<char>&) os) << val;
}

LOG4XX_INFO宏扩展到:

#define LOG4CXX_INFO(logger, message) { 
    if (logger->isInfoEnabled()) {
       ::log4cxx::helpers::MessageBuffer oss_; 
       logger->forcedLog(::log4cxx::Level::getInfo(), oss_.str(oss_ << message), LOG4CXX_LOCATION); }}

MessageBuffer也"定义"了这个运算符:

// messagebuffer.h
template<class V>
std::ostream& operator<<(MessageBuffer& os, const V& val) {
    return ((std::ostream&) os) << val;
}

我不明白如何以正确的方式重载该运算符以使其工作。知道吗?

您可以尝试在命名空间 std 中声明运算符<<(这是合法的,因为您要传递用户定义类型的实例):

namespace std {
   ostream& operator<<(ostream& os, const A& a);
}

Alan将用户定义的运算符放在std命名空间中的建议有效。但我更喜欢将用户定义的运算符放在 log4cxx::helpers 命名空间中,这也有效。具体说来

namespace log4cxx { namespace helpers {
    ostream& operator<<(ostream& os, const A& a);
} }

我现在没有可用的编译器,但我认为问题是由尝试在常量字符串上使用插入运算符引起的。 "A: " << a