2011-04-28 162 views
8

如何在C++中編寫用戶自定義流操作器來控制流式自編寫類的格式?如何編寫自定義流式自定義操作器

具體來說,我將如何編寫簡單的機械手verboseterse來控制輸出流量?

我的環境是GCC 4.5.1及更高版本。

例子:

class A 
{ 
... 
}; 

A a; 

// definition of manipulators verbose and terse 

cout << verbose << a << endl; // outputs a verbosely 
cout << terse << a << endl; // outputs a tersely 

PS:接下來只是一個方面的問題,可隨時忽略它:可以這樣便攜擴展到以參數操縱? Josuttis在第13.6.1節結尾附近的「C++標準庫」中寫道,編寫操縱符號參數取決於實現。這仍然是真的嗎?

+0

不是重複的,而是相關的(有趣的)主題:[流操縱器如何工作?](http://stackoverflow.com/questions/4633864/how-do-the-stream-manipulators-work) – Nawaz 2011-04-28 12:24:24

回答

2

我沒有看到任何理由讓他們依賴實施。

這是我使用的東西,對於實際的操縱器,創建一個返回以下幫助器實例的函數。如果你需要存儲數據,只是將其存儲幫手,一些全局變量,單,等裏面......

/// One argument manipulators helper 
    template < typename ParType > 
    class OneArgManip 
    { 
     ParType par; 
     std::ostream& (*impl)(std::ostream&, const ParType&); 

     public: 
      OneArgManip(std::ostream& (*code)(std::ostream&, const ParType&), ParType p) 
       : par(p), impl(code) {} 

      // calls the implementation 
      void operator()(std::ostream& stream) const 
      { impl(stream,par); } 

      // a wrapper that allows us to use the manipulator directly 
      friend std::ostream& operator << (std::ostream& stream, 
          const OneArgManip<ParType>& manip) 
      { manip(stream); return stream; } 
    }; 

例如基於這樣的機械手:

OneArgManip<unsigned> cursorMoveUp(unsigned c) 
{ return OneArgManip<unsigned>(cursorMoveUpI,c); } 

std::ostream& cursorMoveUpI(std::ostream& stream, const unsigned& c) 
{ stream << "\033[" << c << "A"; return stream; } 

對於一些解釋:

  1. u使用機械手,返回綁定到助手的實現助手的新實例
  2. 流嘗試處理助手,調用助手中
  3. <<重載調用()運營商的幫手
  4. 調用真正的實現與原來的機械手調用中傳遞的參數輔助的

如果你想我也可以發佈2個參數和3個參數助手。原則是相同的。

+0

謝謝,但是我想到操縱器會影響後續項目的流式傳輸。 – 2011-04-28 20:59:58

+0

@彼得是一回事。您只需將設置存儲在某個地方。而不是將某些東西輸出到流中,而是設置'YourClass :: outputtype'或類似的東西。 – 2011-04-28 21:30:21