Incorrect operator<< is called.

T

Terry Santegoeds

Can someone explain what's going on with the test program below ?

On Windows / Visual Studio .NET

os << x << endl; uses operator<< ( ostream & , const string & )

but

cout << x << endl; uses operator<< ( ostream & , const X & ) as I expect.

On Linux / g++, operator<< ( ostream & , const X & ) is used in both cases.

Is this a bug on Windows or is there something in the standard that I'm not
aware off ?

Test program:

#include <iostream>
#include <istream>
#include <string>
#include <sstream>

using namespace std;

class X
: public string
{ };

ostream& operator<< ( ostream& strm, const X& x )
{
strm << "Okidoki : '" << static_cast<string>( x ) << "'";
return strm;
}

int main( void )
{
X x;
ostringstream os;

os << x << endl;

cout << os.str( );

return 0;
}

Thanks.
 
L

Leor Zolman

After replying to this a minute ago and selecting "reply to all groups", I
remembered something about how crossposted messages are held up from being
posted to the non-moderated groups until the moderated ones accept it.
Since it can take a while for stuff to show up on clcm, I'll risk some ire
and post this again /just here/ so that folks might benefit from the
research I put into this. Sorry in advance for when (if?) it shows up
again...

-----------------

I've spent a while trying to pin this one down, and all I've managed to
accomplish so far is to get frustrated. First, note that the problem only
happens under VC6 and VC7.0 (under VC7.1 it works fine, as it does under
every other platform I have handy here to test on.) I've found several ways
to work around the problem, the simplest being to just cast the stream in
your insertion statement thusly:

(ostream &) os << x << endl;

Another thing you can do (in order to avoid adding the ugly casts
everywhere) would be to define another inserter that takes an ostringstream
rather than an ostream:

ostream& operator<< ( ostringstream& strm, const X& x )
{
strm << "Okidoki : '" << static_cast<string>( x ) << "'";
return strm;
}

All this leads me to suspect that either some template support deficiency
in the VC6/7.0 compiler is the culprit, or else it is something in the
libraries they use. However, the fact I get exactly the same (wrong)
behavior when using the Dinkum drop-in replacement libs with VC6 and VC7.0
makes me lean toward suggesting it is the compilers that are to blame.

HTH,
-leor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top