The title is my question. basic_ostream has both types of the insertion operator. The free operator<< is for chars and the member operator<< is for non char data.
Why is there a need to implement some as free function and others as member function?
They could have all been implemented as free functions, and that is the preferred usage nowadays. Back when iostreams was created, they might have been trying to keep the overload set small.
There's a lot of weirdness in the iostreams and locale libraries; they should not be used as model desgins.
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 ifstream object will not bind to a reference parameter, but it will bind to this.
That's pretty much the only difference between the member and non-member versions. C++11 smoothed over this difference with rvalue references. (There's also the way you would call them without operator overloading, like cin.operator >> ( i ), but nobody ever does that.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With