天天看點

編寫自己的流操作程式 經典代碼

  自己寫程式實作一個流操作符來完成流操作或者标準流不能完成的工作。或者自己自己寫程式實作單個操作符來在一個流上設定多個标志而不是每次都調用多個操作符。

  下面請看一個簡單的流操作程式:

#include <iostream>

#include <string>

  using namespace std;

  inline ios_base& floatnormal(ios_base& io) {

  io.setf(0, ios_base::floatfield);

  io.precision(4);

  io.width(10);

  return io;

}

  int main()

{

  ios_base::fmtflags flags = cout.flags();  //儲存原有的流标志

  double pi = 3.14159265;

  cout << "pi=" << floatnormal << pi << std::endl;

  cout.flags(flags);    //恢複原有的流标志

  return 0;

  這裡需要注意的是要儲存原有的流标志,因為一旦使用流操作後,後續的流标志都會被修改,setw()除外。是以需要恢複原有的流标志,當然如果後續的流操作都使用相同的格式,不需要恢複。

  從這段代碼代碼可以看出,寫字的流操作程式看起來是很簡單的。但是如果要編寫帶有參數的的流操作呢?如:floatnormal(n),該如何編寫呢?這就比較複雜了,而且要想寫通用一些,更加需要較深的程式設計經驗。

  筆者在這裡有一個例子,供大家參考。這段代碼比較經典,使用模闆和函數指針也比較出色。

  template<typename T, typename C>

class ManipInfra

  private:

    T val_;

    basic_ostream<C>& (*manipFun_)(basic_ostream<C>&, T );

  public:

    ManipInfra(basic_ostream<C>& (*pFun)(basic_ostream<C>&, T), T val)

      : manipFun_ (pFun), val_(val){

    }

    void operator()(basic_ostream<C>& os) const {

      manipFun_(os, val_);

};

basic_ostream<C>& operator<<(basic_ostream<C>& os, const ManipInfra<T, C>& manip) {

  manip(os);

  return os;

  ostream& setTheWidth(ostream& os, int n) {

  os.width(n);

  ostream& setTheFill(ostream& os, char c) {

  os.fill(c);

  ManipInfra<int, char> setWidth(int n) {

  return ManipInfra<int, char>(setTheWidth, n);

  ManipInfra<char, char> setFill(char c) {

  return ManipInfra<char, char>(setTheFill, c);

  cout << setFill('*') << setWidth(19) << right << "djf\n";

     本文轉自panpan3210 51CTO部落格,原文連結:http://blog.51cto.com/panpan/116853,如需轉載請自行聯系原作者

繼續閱讀