I have a special type of ostringstream that I am trying to output text as a temporary object, but I have problems. To be clear, this is essentially what I want to do:
ostringstream() << "PARTY DOWN!" << endl;
Now, before you say: βBut Zach, this code is completely useless! The object is destroyed at the end of the line, how would you even know that he did something?β, Listen to me. I am not trying to do this with a simple ostringstream, but rather from a derived class in which the destructor actually provides a way to output data from the object. So it actually looks a lot bigger:
specialstringstream() << "PARTY DOWN!" << endl;
If specialstringstream has a destructor that unloads text elsewhere.
I will not go into details why I do it. You will have to trust me that this makes sense for what I need to do, and it fits perfectly into the existing gigantic code base.
Here's the problem: when I do this, everything compiles and starts, but I get the address of the pointer printed on my output, instead of "PARTY DOWN!". line. I decided that this was because the operator selected by the compiler to execute the stream was ostream& operator<< (const void* val) and not ostream& operator<< (ostream& out, const char* s ) .
I have a vague idea of ββwhy, but I donβt understand how this works. What can I do to get char * s to print to a temporary stringstream instance?
Here is a short version of the SpecialStringStream object that demonstrates the behavior:
class SpecialStringStream : public ostringstream { public: SpecialStringStream(ostream* regularStream) { regularStream_ = regularStream; } ~SpecialStringStream() { if (regularStream_ != NULL) (*regularStream_) << str(); } private: ostream* regularStream_; };
When I do something like: SpecialStringStream(someStreamPtr) << "PARTY DOWN!" << endl; SpecialStringStream(someStreamPtr) << "PARTY DOWN!" << endl; , I get the address of the pointer, such as "00444D60" in my message, and not in the message.
EDIT: Since I'm too new to answering my own question, this is what I decided thanks to all the answers.
I came up with the following solution that works under Visual C ++ 8 and all the other compilers I needed. I created a template statement that basically splits the const SpecialStringStream of its constant, discards it as ostream and allows the ostream operators to do their job. Feel free to tear it to shreds in the comments and warn me about all the terrible potential mistakes that I have presented!
template <class T> std::ostream& operator<<(const SpecialStringStream &o, T msg) { return static_cast<std::ostream&>(const_cast<SpecialStringStream&>(o)) << msg; }