Click here to Skip to main content
Click here to Skip to main content

Overloading streams

, 7 Oct 2003
Rate this:
Please Sign up or sign in to vote.
An article on overloading streams.

Introduction

I have found one difference between iostream library and standard libc in the way they handle I/O. The files really don’t care, to which device or regular file they are pointing to, as long as data is appropriate. Where as streams basically differ in the way they behave when it comes to files and console, as these functions are performed by different classes. It is quite well justified to behave that way.

But a programmer need not to worry whether his class is being outputted to file or standard console as long as stream supports operator << for built in data types.

There is a way to provide this transparency using templates.

Using the code

Assume that you have some class SomeClass which you want it to output to some stream. You really don’t care to which stream its being outputted.

It may be ostream(cout) or some fstream.

1.class SomeClass 
2.{ 
3.public: 
4.explicit SomeClass(int x) 
5.{ 
6.this->x = x ; 
7.} 
 

…………………………………….

…………………………………
8.template<class T> 
9.friend T& operator<<(T& os, const SomeClass &d) //Overloaded operator <<.
10.{ 
11.os<<d.x; 
12.return os; 
13.} 
 
14.private: 
15.int x; 
16.};

The same thing holds good for input streams and implementation can be found in the source code file.

Points of interest

If you are writing constructor for SomeClass, make sure that it is explicit. Otherwise it will try to convert d.x (Line no. :11) to SomeClass object thus resulting in compile time error. { I have wasted half an hour to figure it out. Wink | ;) }

Conclusion

Templates provide a great power when it comes to producing generic code. Use them to create reusable, generic code. Have fun;).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Prasad Kulkarni

United States United States
No Biography provided

Comments and Discussions

 
QuestionWhat's new? PinsussAnand Paranjpe8-Oct-03 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 8 Oct 2003
Article Copyright 2003 by Prasad Kulkarni
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid