自定义重载运算符 << 与 log4cxx

Custom overload operator<< with log4cxx

我有以下代码:

namespace foo {
namespace bar {
class Baz {
protected:
    void print(std::ostream&);
public:
    friend std::ostream& operator<<(std::ostream& o, Baz& b) {
        b.print(o);
        return o;
    }
}}}

然后在另一个文件中:

Baz* b = getBaz();
LOG4CXX_INFO(logger, "Baz is " << *b);

我收到来自 gcc 的错误消息:

error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'

看起来混乱是因为在 log4cxx 中定义了这个重载

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

我尝试通过以下方式修改我的代码:

//forward declaration
namespace foo {
namespace bar {
class Baz;
}
}

namespace std {
using foo::bar::Baz;
//implementation in cpp file
std::ostream& operator<<(std::ostream& o, Baz& b);
}

namespace foo {
namespace bar {
class Baz {
protected:
    void print(std::ostream&);
public:
    friend std::ostream& std::operator<<(std::ostream& o, Baz& b);
}}}

但是代码再次失败并出现相同的错误。如何强制编译器使用我自己的运算符版本?

看来您应该将 Baz& 参数声明为 const Baz& 并且 print 方法也应该声明为 const.

namespace foo {
namespace bar {

class Baz {
protected:
    void print(std::ostream&) const;
public:
    friend std::ostream& operator<<(std::ostream& o, const Baz& b) {
        b.print(o);
        return o;
    }
};

}}