I'd like implement class MyCout
, which can provide possibility of automatic endl, i.e. this code
MyCout mycout;
mycout<<1<<2<<3;
outputs
123
//empty line here
Is it possible to implement class with such functionality?
UPDATE:
Soulutions shouldn't be like that MyCout()<<1<<2<<3;
i.e. they should be without creating temporary object
You can use the destructor of a temporary object to flush the stream and print a newline. The Qt debug system does this, and this answer describes how to do it.
The following works in C++11:
#include <iostream>
struct myout_base { };
struct myout
{
bool alive;
myout() : alive(true) { }
myout(myout && rhs) : alive(true) { rhs.alive = false; }
myout(myout const &) = delete;
~myout() { if (alive) std::cout << std::endl; }
};
template <typename T>
myout operator<<(myout && o, T const & x)
{
std::cout << x;
return std::move(o);
}
template <typename T>
myout operator<<(myout_base &, T const & x)
{
return std::move(myout() << x);
}
myout_base m_out; // like the global std::cout
int main()
{
m_out << 1 << 2 << 3;
}
With more work, you can add a reference to the actual output stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With