How are iomanip functions implemented?

Some of the standard iomanip functions accept a parameter.

I would like to know how this is achieved, for example, can I do something similar with a function? This is really the solution that I needed to answer , but I could not figure out how to do this.

When I looked at the definition for the setw function setw for example, at http://en.cppreference.com, it lists the return type as "undefined" and also lists only one argument, instead of taking the stream& parameter. How it works?

Note to the reader:

There is an excellent answer to this question , but for a person seeking this question; this answer will only be useful in combination with the following features provided by ios_base :

+7
source share
1 answer

Here is a simple example of a custom manipulator that takes a single parameter defined using a class:

 #include <iostream> class putX // injects some `X`s into the stream { std::size_t _n; public: explicit putX(std::size_t n): _n(n) {} std::size_t getn() const {return _n;} friend std::ostream& operator<<(std::ostream& os, const putX& obj) { std::size_t n = obj.getn(); for (std::size_t i = 0; i < n; ++i) os << 'X'; return os; } }; int main() { std::cout << putX(10) << " test " << putX(10); } 

Manipulators that do not accept parameters can simply be implemented as

 std::ostream& custom_manip(std::ostream& os) { // do something with os and return os;} 

This is because basic_ostream::operator<< has an overload that takes a pointer to the function std::ostream& (*fp)(std::ostream&) as the right part (for example, a manipulator)

PS: N. Josuttis C ++ Standard Library describes how manipulators / user manipulators work in great detail, see chap. 15.6.3 User Manipulators

+6
source

Source: https://habr.com/ru/post/984407/


All Articles