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);
}}}
然而,使用相同的错误代码仍然失败。 我如何强制编译器使用我的操作符版本?