Is it possible to write a method that takes a stringstream and have it look something like this,
void method(string st
For ease of writing objects that can be inserted into a stream, all these classes overload operator<<
on ostream&
. (Operator overloading can be used by subclasses, if no closer match exists.) These operator<<
overloads all return ostream&
.
What you can do is make the function take an ostream&
and dynamic_cast<>
it to stringstream&
. If the wrong type is passed in, bad_cast
is thrown.
void printStringStream(ostream& os) {
stringstream &ss = dynamic_cast(os);
cout << ss.str();
}
Note: static_cast<>
can be used, it will be faster, but not so bug proof in the case you passed something that is not a stringstream
.