Why does std :: basic_ostream have both free and the member operator <<?

The title is my question. basic_ostream has both types of insert operator. The free operator << is for characters and the member <is for non-char data.

Why is there a need to implement some function as free and others as member?

+3


source share


1 answer


They could be implemented as free features, which is the preferred use at this time. Back when the iostreams were created it may have been trying to keep the overload size small.

There's a lot of weirdness in the iostreams and locale libraries; they should not be used as model designs.

In C ++ 98, you can do

int i;
std::ifstream( "data" ) >> i;

      



but you cannot do

std::string s;
std::ifstream( "data" ) >> s;

      

The temporary object ifstream

will not be bound to the reference, but it will be bound to this

.

This is pretty much the only difference between member and non-member versions. C ++ 11 flattens out this difference with rvalue references. (You can also call them without operator overloading, for example cin.operator >> ( i )

, but nobody ever does that.)

+10


source







All Articles