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

偶尔善良 提交于 2019-11-28 03:21:21

问题


Say I have a class A and an operator<< declared like so:

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

somewhere else I use my logger with A:

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

The compiler is complaining: binary '<<' : no operator found which takes a right-hand operand of type 'const A' (or there is no acceptable conversion) D:\dev\cpp\lib\apache-log4cxx\log4cxx\include\log4cxx\helpers\messagebuffer.h 190

This error takes me to the declaration of the 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 macro expands to:

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

MessageBuffer "defines" this operator as well:

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

I don't understand how to overload this operator the right way to make it work. Any idea?


回答1:


You could try declaring your operator << in namespace std (that's legal, since you're passing an instance of your user-defined type):

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



回答2:


Alan's suggestion of putting the user-defined operator in the std namespace works. But I prefer putting the user-defined operator in the log4cxx::helpers namespace, which also works. Specifically,

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



回答3:


I don't have a compiler available right now but i think the problem is caused by trying to use insert operator on a constant string. "A: " << a



来源:https://stackoverflow.com/questions/5990898/how-to-overload-the-ostream-operator-to-make-it-work-with-log4cxx-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!