I was messing around with std::ostringstream
whilst looking at this question: sprintf in c++?, and noticed the stringbuilder()
wrapper by Nawaz and thought, well that ought to work with std::ostringstream
.
So my first attempt was the following:
std::cout << (std::ostringstream("select * from foo limit") << max_limit).str() << std::endl;
Now this obviously fails to compile (correctly) as the result of the operator<<
is a std::ostream
- which doesn't have the member str()
. So I thought a cast should do the trick, and specifically a cast to a const
reference (works with a cast to a normal reference too), so second attempt:
std::cout << static_cast<std::ostringstream const&>(std::ostringstream("select * from foo limit") << max_limit).str() << std::endl;
Now this compiles fine and runs, however the output is, well, not what I was expecting.
10lect * from foo limit
Now - here's the question, am I invoking some undefined behaviour somewhere - and if so where? And how is this different to the approach that Nawaz has taken (I guess aside from the result of his operator is the stringbuilder
itself rather than std::ostream
).
EDIT: here is the ideone code.
EDIT: oops - forgot to specify, max_limit
is int
.