如何重载 ostream 运算符<<以使其在 C++ 中与 log4cxx 一起使用?
How to overload the ostream operator << to make it work with log4cxx in C++?
假设我有一个类 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
相关文章:
- 在C++游戏中与库存系统作斗争
- 如何打印源文件中与 GDB 中的程序流关联的所有行号
- 访问 std:vector 的类成员 std:vector 在一个类中与另一个 std:vector
- 比较两个整数在C++中与未知 int 类型的相等性
- 通用MOCK_METHOD在 gMock 中与MOCK_METHODn相比有什么好处
- 我怎样才能简单地将opencv 包含在我的项目中与CMake
- 如何在扩展的QQuickItem中与模型交互
- C++ 在 CentOS7 中与 g++ 的 DLL 链接后未声明的函数
- Qt 应用程序中与Qt版本相关的运行时错误
- 在C 语言中与字符串重复的混淆
- 我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
- 在Visual C ++中与Stockfish(外部可执行文件)通信的最佳方式
- 在多个文件中与同一类分开函数
- 在DirectX Math中与XmmatrixDecompose()相反
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- UART在Gem5中与手臂裸机中的通信
- 在CPP中与2D矢量合作
- 如何修复结构播放器对象中的矢量位置,以便它在 Main 中与 me.position 一起使用?
- 在 c++ 中与大型代码库作斗争
- 包装在 do-while-0 中与包装在带有 (void)0 的三元运算符中