Download C++ Library Reference - Oracle Documentation

Transcript
■
The manipulator. It takes an extra parameter. In the previous code example, it takes
an extra int parameter. You cannot place this manipulator function in a sequence
of input or output operations, since there is no shift operator defined for it.
Instead, you must use an auxiliary function, the applicator.
■
The applicator. It calls the manipulator. The applicator is a global function, and
you make a prototype for it available in a header file. Usually the manipulator is
a static function in the file containing the source code for the applicator. The
manipulator is called only by the applicator, and if you make it static, you keep
its name out of the global address space.
Several classes are defined in the header file iomanip.h. Each class holds the
address of a manipulator function and the value of one parameter. The iomanip
classes are described in the man page manip(3CC4). The previous example uses the
smanip_int class, which works with an ios. Because it works with an ios, it also
works with an istream and an ostream. The previous example also uses a second
parameter of type int.
The applicator creates and returns a class object. In the previous code example the
class object is an smanip_int, and it contains the manipulator and the int
argument to the applicator. The iomanip.h header file defines the shift operators
for this class. When the applicator function setfill appears in a sequence of input
or output operations, the applicator function is called, and it returns a class. The
shift operator acts on the class to call the manipulator function with its parameter
value, which is stored in the class.
In the following example, the manipulator print_hex:
■
■
■
Puts the output stream into the hex mode.
Inserts a long value into the stream.
Restores the conversion mode of the stream.
The class omanip_long is used because this code example is for output only, and it
operates on a long rather than an int:
#include <iostream.h>
#include <iomanip.h>
static ostream& xfield(ostream& os, long v) {
long save = os.setf(ios::hex, ios::basefield);
os << v;
os.setf(save, ios::basefield);
return os;
}
omanip_long print_hex(long v) {
return omanip_long(xfield, v);
}
Chapter 3
The Classic iostream Library
3-19