Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 438
quant Avatar asked Jun 05 '26 20:06

quant


1 Answers

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.

like image 117
Sergey Kalinichenko Avatar answered Jun 07 '26 08:06

Sergey Kalinichenko