Mycout automatic endl

I would like to implement the MyCout class, which can provide the ability to automatically endl, i.e. this code

 MyCout mycout; mycout<<1<<2<<3; 

exits

 123 //empty line here 

Is it possible to implement a class with such functionality?


UPDATE: Soulutions should not be like MyCout()<<1<<2<<3; that is, they should be without creating a temporary object

+6
source share
4 answers

This is just a Rob answer option that doesn't use a bunch. This is a pretty big change that I didn’t just want to change his answer, although

 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() { 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(os) << t; } int main () { MyCout mycout; mycout << 1 << 2 << 3; mycout << 3 << 4 << 5; MyCout mycerr(std::cerr); mycerr << 6 << "Hello, world" << "!"; } 
+2
source

You can use the temporary object's destructor to clear the stream and print a new line. The Qt debugging system does this, and this answer describes how to do it.

+8
source

In C ++ 11, the following works:

 #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 extra work, you can add a link to the actual output stream.

+7
source

If you need to avoid the features of C ++ 11:

 #include <iostream> #include <sstream> #include <memory> struct MyCout { MyCout(std::ostream& os = std::cout) : os(os) {} struct A { A(std::ostream& os) : os(os) {} A() : os(os) {} ~A() { os << std::endl; } std::ostream& os; }; std::ostream& os; }; template <class T> const std::auto_ptr<MyCout::A>& operator<<(const std::auto_ptr<MyCout::A>& a, const T& t) { a->os << t; return a; } template<class T> const std::auto_ptr<MyCout::A> operator<<(MyCout& m, const T& t) { std::auto_ptr<MyCout::A> p(new MyCout::A(m.os)); p << t; return p; } int main () { MyCout mycout; mycout << 1 << 2 << 3; mycout << 3 << 4 << 5; MyCout mycerr(std::cerr); mycerr << 6 << "Hello, world" << "!"; } 
+1
source

Source: https://habr.com/ru/post/903794/


All Articles