• 13
• 18
• 19
• 27
• 10

# ostringstream compilation issue

This topic is 2765 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi,
I am not sure why the below is failing to compile.

It fails with the below error...

invalid initialization of reference of type ‘std::ostringstream&’ from expression of type ‘std::basic_ostream<char, std::char_traits<char> >’

    #include <iostream>    #include <sstream>    #include <string>    using namespace std;        void printOStream(ostringstream &x)    {            cout<<x.str();    }        int main()    {            int x = 10;            ostringstream out;            printOStream(out<<"the error is "<<x<<endl);            return 0;    }

:(

##### Share on other sites
Quote:
 Original post by _korgHi,I am not sure why the below is failing to compile. It fails with the below error...invalid initialization of reference of type ‘std::ostringstream&’ from expression of type ‘std::basic_ostream >’*** Source Snippet Removed ***:(

If you want to do something like that, then adding default parameter might help.
void print(const string& msg, ostream& out = cout){ out << msg;}//now the call could be anything object that was derived from ostream or an //object from ostream it selfprint("hello");print("writeThisToFile",oFile);print("writeThisToStream",ostringstreamObject);//...

##### Share on other sites
Here's the problem: you want to pass an ostringstream, specifically, so that you can make the .str() call within the function. But applying operator<< to an ostream loses the information about what kind of ostream it is.

For the same reason, you cannot just call the .str() outside the function on the temporary. The simplest solution is to do the operator chaining in a separate statement, thus:

int x = 10;ostringstream out;out<<"the error is "<<x<<endl;// now we can doout.str();// orprintOStream(out);

There are ways to get around this with casting, but they are more difficult, much more complicated than one might initially expect, incredibly ugly and possibly (IIRC) unsafe.