Manipulator infrastructure - C++ File Stream

C++ examples for File Stream:cout

Description

Manipulator infrastructure

Demo Code

#include <iostream>
#include <string>

using namespace std;

template<typename T, typename C>
class MyFormat {//from   www  .  j  a  va2 s . c  o m
public:
   MyFormat (basic_ostream<C>& (*pFun) (basic_ostream<C>&, T), T val) : manipFun_(pFun), val_(val) {}
   void operator()(basic_ostream<C>& os) const
      {manipFun_(os, val_);}
private:
   T val_;
   basic_ostream<C>& (*manipFun_)
      (basic_ostream<C>&, T);
};

template<typename T, typename C>
basic_ostream<C>& operator<<(basic_ostream<C>& os, const MyFormat<T, C>& manip) {
   manip(os);
   return(os);
}

ostream& setTheWidth(ostream& os, int n) {
   os.width(n);
   return(os);
}

MyFormat<int, char> setWidth(int n) {
   return(MyFormat<int, char>(setTheWidth, n));
}

ostream& setTheFillChar(ostream& os, char c) {
   os.fill(c);
   return(os);
}

MyFormat<char, char> setFill(char c) {
   return(MyFormat<char, char>(setTheFillChar, c));
}

int main() {
  cout << setFill('-') << setWidth(10) << right << "test\n";
}

Result


Related Tutorials