title: Writing a manipulator for a custom stream class
body: <p>I've written a custom stream class that outputs indented text and that has manipulators that can change the indent level. All of the indenting work is implemented in a custom stream buffer class, which is used by the stream class. The buffer is working (i.e. text is indented in the output), but I can't get my manipulators to work. I was reading in a lot of places how ostream (which my class extends) overloads the operator&lt;&lt; like this:</p>
  
  <pre><code>ostream&amp; ostream::operator &lt;&lt; ( ostream&amp; (*op)(ostream&amp;))
  
  {
      // call the function passed as parameter with this stream as the argument
      return (*op)(*this);
  }
  </code></pre>
  
  <p>Which means it can take in a function as a parameter. So why aren't my "indent" or "deindent" stream functions being recognized? I'm sure I have to do some overloading of operator&lt;&lt;, but shouldn't I not need to? See below for my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;streambuf&gt;
  #include &lt;locale&gt;
  #include &lt;cstdio&gt;
  
  using namespace std;
  
  class indentbuf: public streambuf {
  
  public:
  
      indentbuf(streambuf* sbuf): m_sbuf(sbuf), m_indent(4), m_need(true) {}
  
      int indent() const { return m_indent; }
      void indent() { m_indent+=4; }
      void deindent() { if(m_indent &gt;= 4) m_indent-= 4; }
  
  protected:
  
      virtual int_type overflow(int_type c) {
  
          if (traits_type::eq_int_type(c, traits_type::eof()))
  
              return m_sbuf-&gt;sputc(c);
  
          if (m_need)
          {
              fill_n(ostreambuf_iterator&lt;char&gt;(m_sbuf), m_indent, ' ');
              m_need = false;
          }
  
          if (traits_type::eq_int_type(m_sbuf-&gt;sputc(c), traits_type::eof()))
  
              return traits_type::eof();
  
          if (traits_type::eq_int_type(c, traits_type::to_char_type('\n')))
  
              m_need = true;
  
          return traits_type::not_eof(c);
      }
  
      streambuf* m_sbuf;
      int m_indent;
      bool m_need;
  };
  
  class IndentStream : public ostream {
  public:
      IndentStream(ostream &amp;os) : ib(os.rdbuf()), ostream(&amp;ib){};
  
      ostream&amp; indent(ostream&amp; stream) {
          ib.indent();
          return stream;
      }
  
     ostream&amp; deindent(ostream&amp; stream) {
          ib.deindent();
          return stream;
      }
  
  private:
      indentbuf ib;
  };
  
  int main()
  {
      IndentStream is(cout);
      is &lt;&lt; "31 hexadecimal: " &lt;&lt; hex &lt;&lt; 31 &lt;&lt; endl;
      is &lt;&lt; "31 hexadecimal: " &lt;&lt; hex &lt;&lt; 31 &lt;&lt; endl;
      is &lt;&lt; "31 hexadecimal: " &lt;&lt; hex &lt;&lt; 31 &lt;&lt; deindent &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  
  <p>Thanks! </p>