quant quant - 1 year ago 85
C++ Question

How do I stream into a string without creating a named stringstream?

I often end up writing code like this:

SomeStreamableType x;
std::stringstream ss;
ss << "Value is: " << x;

The extra line needed to generate the stringstream feels superfulous. I can do this, but it's equally cumbersom:

SomeStreamableType x;
const std::string str = "Value is: " + boost::lexical_cast<std::string>(x);

I want to be able to do this:

SomeStreamableType x;
log(std::stringstream() << "Value is: " << x);

Have others encountered this issue and come up with a workaround? I don't want to create any helper functions or classes.

Answer Source

Your code will work without modifications, as long as log accepts an ostream& reference:

void log(ostream& o) {
    stringstream* s = dynamic_cast<stringstream*>(&o);
    if (s) {
        cout << s->str() << endl;

int main() {
    int x = 5, y = 6;
    log(stringstream() << "x=" << x << ", y=" << y);
    return 0;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download