MESSAGE
DATE | 2011-07-07 |
FROM | Ruben Safir
|
SUBJECT | Subject: [NYLXS - HANGOUT] (fwd) iostream manipulator construction and design
|
-- forwarded message -- Path: reader1.panix.com!panix!not-for-mail From: Ruben Safir Newsgroups: comp.lang.c++ Subject: iostream manipulator construction and design Date: Wed, 6 Jul 2011 02:55:09 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 67 Message-ID: NNTP-Posting-Host: www2.mrbrklyn.com Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: reader1.panix.com 1309920909 10928 96.57.23.82 (6 Jul 2011 02:55:09 GMT) X-Complaints-To: abuse-at-panix.com NNTP-Posting-Date: Wed, 6 Jul 2011 02:55:09 +0000 (UTC) User-Agent: Pan/0.133 (House of Butterflies) Xref: panix comp.lang.c++:1087303
I've covered the iostream operations in Stroustrup but there is a section that I'm failing to understand in section 21.4.6.1 (of the third edition of C++ - The Programming Language) which I hope that someone can help me decipher. The section discusses Manipultors that take arguments and Stroustrup states
"Manipulators that take arguments can also be useful. For example, we might want to write
cout << setprecision(4) << angle;
to print the value of the floating-point variable angle with four digits.
To do this, setprecision must return an object that is initialized by 4 and that calls cout::setprcision when involked. Such a manipulator is a function object thatr is involed by << rather than by (). The exact tyoe of function object is implementation-defined, but it might be defined like this:
struct smanip{ ios_base& (*f)(ios_base&, int); //function to be called int i;
smanip(ios_base& (*ff) (ios_base&, int), int ii) : f(ff, i(ii){} };
template ostream& operator<<(ostream& os, smanip& m) { return m.f(os, m.i); }
The smanip constructor stores its arguments in f and i and the operator<< calls f(i). We can now define setprecision() like this:
ios_base& set_precision(ios)base& s, int n) //helper { return s.setprecision(n); //call member function }
inline smap setprecision(int n) { return smanip(set_precision, n); }
We can now write: cout << setprecision(4) << angle; "
What don't understand a couple of things here, and this might be an accumulation of increasing confusion on my part as I've continued through this chapter.
First, I just don't understand what the problem is that is being solved. Why can't a manipulator just take an argument of an int and return a base_stream object, like the manipulators that don't take an argument?
Secondly, the exqmple completely befuddles me. I'm guessing that don't understand the order of operations of
cout << setprecision(4) << angle;
is ostream<< called first and then the function setprecision?
-- end of forwarded message --
|
|