Writing ‘endl’ like functions for output streams

Ever wondered how endl works! Quite simple, endl is just a function with a predefined signature and output streams has ‘operator <<‘ overloaded to take function pointers which satisfy this particular signature, so whenever it finds such a function the compiler just calls this operator with argument set to pointer to this function which in turn calls this function.

Code for endl looks like this…

[sourcecode language=’cpp’]_CRTIMP inline basic_ostream >&
__cdecl endl(basic_ostream< char, char_traits >& _O)
{
      _O.put(‘n’);
      _O.flush();
      return (_O);
}[/sourcecode]

Code for overloaded ‘operator <<‘ looks likewise.

[sourcecode language=’cpp’]_Myt& operator< <(_Myt& (__cdecl *_F)(_Myt&)) {return ((*_F)(*this)); }[/sourcecode] So from above code snippets we can see that when we call endl it flushes (_O.flush()) given stream too after inserting a newline character. So to write an 'endl' like function we should provide functions with exactly same signature. Signature is as follows... [sourcecode language='cpp']_Myt& (__cdecl *_F)(_Myt&)[/sourcecode] Where '_Myt' is the reference to given stream. So we are now going to write few similar functions like endl...

  1. tab function- inserts a tab characters
  2. beep function – beeps
  3. [sourcecode language=’cpp’]#include
    inline ostream& __cdecl tab( ostream& strm )
    {
       strm.put( ‘t’ );
       return strm;
    }

    inline ostream& __cdecl beep( ostream& strm )
    {
       strm.put( ‘a’ );
       return strm;
    }

    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    {
        cout << "Nibu" << tab << "babu" << tab << "Thomas" << beep << beep << beep << endl;     return 0; }[/sourcecode] So output of above code will be, every word in my name separated by a tab followed by three beeps. Note that these functions are inline so no function call overhead but instead makes our code more lucid.

Appreciate your comments...