Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

33.1 A Recap of Manipulators

We showed examples of manipulators in Section 28.3. There we learned that:

As a recap, here is a typical example of two manipulators:

The inserted objects std::setw(10) and std::endl are the manipulators. As its only side effect, the manipulator setw(10) sets the stream's field width to 10. Similarly, the manipulator std::endl inserts the end of line character and flushes the output.

As we mentioned previously, extensibility is a major advantage of iostreams. We've seen in the previous Section 32.3 how you can implement inserters and extractors for user-defined types that behave like the built-in input and output operations. Additionally, you can add user-defined manipulators that fit seamlessly into the iostreams framework. In this section, we show how to do this.

First of all, to be extracted or inserted, a manipulator must be an object of a type that we call manipT, for which overloaded versions of the shift operators exist. (Associated with the manipulator type manipT, there is usually a function called fmanipT()that we explain in detail later.) Here's the pattern for the manipulator extractor:

With this extractor defined, you can extract a manipulator Manip, which is an object of type manipT, by simply saying:

This results in a call to the operator>>() sketched out above. The manipulator inserter is analogous.

A manipulator's side effect is often created by calling an associated function fmanipT() that takes a stream and returns the stream. There are several ways to associate the manipulator type manipT to the function fmanipT(), which we explore in the following sections. The iostream framework does not specify a way to implement manipulators, but there is a simple way to write your own manipulators. We explain this technique along with other useful approaches.

It turns out that there is a major difference between manipulators with parameters like std::width(10) and manipulators without parameters like std::endl. Let's start with the simpler case of manipulators without parameters.

Previous fileTop of DocumentContentsIndex pageNext file