This is simply a variant of Rob's answer, that doesn't use the heap. It's a big enough change that I didn't want to just change his answer though
struct MyCout {
MyCout(std::ostream& os = std::cout) : os(os) {}
struct A {
A(std::ostream& r) : os(r), live(true) {}
A(A& r) : os(r.os), live(true) {r.live=false;}
A(A&& r) : os(r.os), live(true) {r.live=false;}
~A() { if(live) {os << std::endl;} }
std::ostream& os;
bool live;
};
std::ostream& os;
};
template <class T>
MyCout::A operator<<(MyCout::A&& a, const T& t) {
a.os << t;
return a;
}
template<class T>
MyCout::A operator<<(MyCout& m, const T& t) { return MyCout::A(m.os) << t; }
int main () {
MyCout mycout;
mycout << 1 << 2.0 << '3';
mycout << 3 << 4.0 << '5';
MyCout mycerr(std::cerr);
mycerr << 6 << "Hello, world" << "!";
}
MyCout()<<...
or anything – Bogbean