【问题标题】:Custom overload operator<< with log4cxx自定义重载运算符<< 与 log4cxx
【发布时间】:2019-02-20 08:08:46
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

    标签: c++ log4cxx


    【解决方案1】:

    看来Baz&amp;参数应该声明为const Baz&amp;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;
        }
    };
    
    }}
    

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多