Jump to content
  • Advertisement
Sign in to follow this  
_korg

ostringstream compilation issue

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by _korg
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> >’

*** 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 self
print("hello");
print("writeThisToFile",oFile);
print("writeThisToStream",ostringstreamObject);
//...

Share this post


Link to post
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 do
out.str();
// or
printOStream(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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!