I use std::ostringstream
for formatting strings, which inherits its <<
operators from ostream
, and consequently they return an ostream
and not an ostringstream
, which means that I can't call ostringstream::str
on the result. This usually isn't a problem, since I can typically do this:
ostringstream stream;
stream << whatever;
string str = stream.str();
But occasionally I need* to use it in just a single expression, which is more difficult. I could do
string str = ((ostringstream&) (ostringstream() << whatever)).str();
but bad things will happen if that <<
overload returns some ostream
that isn't an ostringstream
. The only other thing I can think to do is something like
string str = ([&] () -> string {ostringstream stream; stream << whatever; return stream.str();})();
but this can't possibly be efficient, and is certainly very bad c++ code.
*Okay, I don't need to, but it would be a lot more convenient to.