Home > C++, VC++ > Writing ‘endl’ like functions for output streams

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…

_CRTIMP inline basic_ostream<char , char_traits<char> >&
__cdecl endl(basic_ostream< char, char_traits<char> >& _O)
      return (_O);

Code for overloaded ‘operator <<‘ looks likewise.

_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. #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.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: