Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an ostringstream in just an expression

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.

like image 796
Anonymous Avatar asked Oct 15 '25 14:10

Anonymous


1 Answers

Using

string str = ([&] () -> string
             {
               ostringstream stream;
               stream << whatever;
               return stream.str();
              })();

is ok. However, I think it will be better to name that operation, create a function with that name, and call the function.

namespace MyApp
{
    template <typename T>
    std::string to_string(T const& t)
    {
        ostringstream stream;
        stream << t;
        return stream.str();
    }
}

and then use

string str = MyApp::to_string(whatever);
like image 116
R Sahu Avatar answered Oct 17 '25 03:10

R Sahu