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:

- Manipulators are objects that can be inserted into or extracted from a stream.

- Such insertions and extractions have specific desirable side effects.

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

    std::cout << std::setw(10) << 10.55 << std::endl;

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 `f` `manipT``()`that we explain in detail later.) Here's the pattern for the manipulator extractor:

    template <class charT, class Traits>
    std::basic istream<charT,Traits>&
    operator>>(std::basic istream<charT,Traits>& istr,
               const manipT& manip)
    {   return fmanipT(istr, ...);   }

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

    std::cin >> Manip;

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 `f` `manipT``()` that takes a stream and returns the stream. There are several ways to associate the manipulator type `manipT` to the function `f` `manipT``()`, 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.