anon anon - 1 month ago 5
C++ Question

Is there anyway to write the following as a C++ macro?

my_macro << 1 << "hello world" << blah->getValue() << std::endl;

should expand into:

std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;


EDIT: the accepted answer is awesome. Can we upvote 8 more times and win this responder a badge?

(The answer only needs 6 more upvotes).

4 more votes to go from 21 to 25.

3 more. :-)

Victory. :-)

#define my_macro my_stream()
class my_stream: public std::ostringstream  {
    my_stream() {}
    ~my_stream() {
int main() {
    my_macro << 1 << "hello world" << std::endl;

A temporary of type my_stream is created, which is a subclass of ostringstream. All operations to that temporary work as they would on an ostringstream.

When the statement ends (ie. right after the semicolon on the whole printing operation in main()), the temporary object goes out of scope and is destroyed. The my_stream destructor calls ThreadSafeLogging with the data "collected" previously.

Tested (g++).

Thanks/credits to dingo for pointing out how to simplify the whole thing, so I don't need the overloaded operator<<. Too bad upvotes can't be shared.