quant
quant

Reputation: 23042

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.

Upvotes: 3

Views: 560

Answers (2)

Galik
Galik

Reputation: 48605

To solve this problem I have often simply done something like this:

#define LOG(m) do{std::ostringstream oss;oss<<m;std::cout<<oss.str()<<'\n';}while(0)

// ...

LOG("some text: " << value1 << ' ' << value2); // no need for '\n'

Now I tend to use a more sophisticated class based solution that has an even nicer interface and doesn't use a horrible macro.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 5

Related Questions