Typically, in C++, we used to define a custom ostream operator<<
this way:
class A {
int impl_;
friend std::ostream& operator<<(std::ostream& os, A const& self){
return os << "A:" << self.impl_;
}
};
However now, post C++11, there are r-value references, and as a matter of fact, built-in types can be streamed to r-value std::ostream
references.
Now this is allowed:
int i = 5;
std::ofstream("file") << i;
(I don't know if this is the reason the special overloads were defined.)
Does it mean that for consistency one should define both operators for custom classes? Like this,
class A {
int impl_;
friend std::ostream& operator<<(std::ostream& os, A const& self) {
return os << "A:" << self.impl_;
}
friend std::ostream&& operator<<(std::ostream&& os, A const& self) {
os << "A:" << self.impl_;
return std::move(os);
}
};
or more streamlined,
class A {
int impl_;
friend std::ostream& operator<<(std::ostream& os, A const& self) {
return os << "A:" << self.impl_;
}
friend std::ostream&& operator<<(std::ostream&& os, A const& self) {
return std::move(os << self); // calls the other overload
}
};
What is the recommended way to overload operator<<
nowadays in C++11?