c++ - How to write a function wrapper for cout that allows for expressive syntax? -
i'd wrap std::cout
formatting, so:
mycout([what type?] x, [optional args]) { ... // formatting on x first std::cout << x; }
and still able use expressive syntax like
mycout("test" << << endl << somevar, indent)
instead of being forced more verbose like
mycout(std::stringstream("test") << ...)
how can implement this? type make x
?
edit: added consideration optional arguments
how this:
struct mycout {}; extern mycout mycout; template <typename t> mycout& operator<< (mycout &s, const t &x) { //format x please std::cout << x; return s; }
and put mycout mycout;
1 .cpp file.
you can use mycout
this:
mycout << "test" << x << std::endl;
and call template operator<<
can formatting.
of course, can provide overloads of operator special formatting of specific types if want to.
edit
apparently (thanks @soon), standard manipulators work, few more overloads necessary:
mycout& operator<< (mycout &s, std::ostream& (*f)(std::ostream &)) { f(std::cout); return s; } mycout& operator<< (mycout &s, std::ostream& (*f)(std::ios &)) { f(std::cout); return s; } mycout& operator<< (mycout &s, std::ostream& (*f)(std::ios_base &)) { f(std::cout); return s; }
edit 2
i may have misunderstoor original requirements slightly. how (plus same manipulator overloads above):
struct mycout { std::stringstream s; template <typename t> mycout& operator << (const t &x) { s << x; return *this; } ~mycout() { somehow_format(s); std::cout << s.str(); } }; int main() { double y = 1.5; mycout() << "test" << y; }
Comments
Post a Comment