The expressionstd::ostringstream()
creates a temporary, and operator<<
which takes const char*
as argument is a free function, but this free function cannot be called on a temporary, as the type of the first parameter of the function is std::ostream&
which cannot be bound to temporary object.
Having said that, <<std::ostringstream() << "some data"
resolves to a call to a member function which is overloaded for void*
which prints the address. Note that a member function can be invoked on the temporary.
In order to call the free function, you need to convert temporary (which is rvalue) into a lvalue, and here is one trick that you can do:
std::cout << "Inline : "
<< dynamic_cast<std::ostringstream&>(
std::ostringstream().flush() << "some data"
).str()
<< "\n";
That is, std::ostringstream().flush()
returns std::ostream&
which means, now the free function can called, passing the returned reference as first argument.
Also, you don’t need to use dynamic_cast
here (which is slow, as it is done at runtime), for the type of the object is pretty much known, and so you can use static_cast
(which is fast as it is done at compile-time):
std::cout << "Inline : "
<< static_cast<std::ostringstream&>(
std::ostringstream().flush() << "some data"
).str()
<< "\n";
which should work just fine.