quant quant - 3 months ago 12
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;
log(ss.str());


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);
log(str);


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

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;
}

Demo.

Comments