65.9K
CodeProject is changing. Read more.
Home

Overloading streams

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.67/5 (15 votes)

Oct 8, 2003

1 min read

viewsIcon

34422

downloadIcon

370

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. ;) }

Conclusion

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