[Assorted-commits] SF.net SVN: assorted:[1482] sandbox/trunk/src/cc/ostream_overload.cc
Brought to you by:
yangzhang
From: <yan...@us...> - 2009-10-13 22:54:06
|
Revision: 1482 http://assorted.svn.sourceforge.net/assorted/?rev=1482&view=rev Author: yangzhang Date: 2009-10-13 22:53:52 +0000 (Tue, 13 Oct 2009) Log Message: ----------- added ostream_overload demo Added Paths: ----------- sandbox/trunk/src/cc/ostream_overload.cc Added: sandbox/trunk/src/cc/ostream_overload.cc =================================================================== --- sandbox/trunk/src/cc/ostream_overload.cc (rev 0) +++ sandbox/trunk/src/cc/ostream_overload.cc 2009-10-13 22:53:52 UTC (rev 1482) @@ -0,0 +1,77 @@ +// <http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16> + +#include <iostream> +#include <iomanip> + +using namespace std; + +// This doesn't work. + +#if 0 + +template<typename T> +class word_fmt +{ + public: + word_fmt(T x) : x_(x) {} + friend ostream & operator<<(ostream &o, word_fmt w); + private: + T x_; +}; + +template<typename T> +ostream & operator<<(ostream &o, word_fmt<T> w) { + o << setfill('0') << setw(8) << hex << w.x_; + return o; +} + +#endif + +// This works. + +#if 0 +template<typename T> +class word_fmt +{ + public: + word_fmt(T x) : x_(x) {} + // Defining in-body works. + friend ostream & operator<<(ostream &o, word_fmt w) { + o << setfill('0') << setw(8) << hex << w.x_; + return o; + } + private: + T x_; +}; +#endif + +// This also works: pre-declaring template, and adding `<>`. + +template<typename T> class word_fmt; +template<typename T> ostream & operator<<(ostream &o, word_fmt<T> w); + +template<typename T> +class word_fmt +{ + public: + word_fmt(T x) : x_(x) {} + // Defining in-body works. + friend ostream & operator<< <>(ostream &o, word_fmt w); + private: + T x_; +}; + +template<typename T> +ostream & operator<<(ostream &o, word_fmt<T> w) { + o << setfill('0') << setw(8) << hex << w.x_; + return o; +} + +// The rest. + +template<typename T> word_fmt<T> word(T x) { return word_fmt<T>(x); } + +int main() { + cout << word(3) << endl; + return 0; +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |