使用log4cxx自定义重载operator<<运算符

3

I have the following code:

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);
}}}

然而,使用相同的错误代码仍然失败。 我如何强制编译器使用我的操作符版本?
1个回答

2

看起来你应该将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;
    }
};

}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接