Re: Is this valid C++ code?
* Brendon Costa:
#include <iostream>
#include <sstream>
// NOTE: The flush is because for some reason passing a string literal
// as the first parameter seemed to display the string literals
address
// as though it was formatting a const void* not a const char* string
literal
#define STR(Message) \
static_cast<std::ostringstream&>(std::ostringstream() \
<< std::flush \
<< Message).str()
The effect of the flush is to give you a reference to an ostream object,
which is an lvalue, rather then the temporary stringstream() object,
which is an rvalue. The difference is that the lvalue can be passed to
formal argument ostream&, whereas the rvalue can't. And the relevant
operator<< is a free-standing operator.
The difference with MSVC 6.0 may be due to a different implementation
of operator<< than the one required by the standard.
void F(const std::string& s)
{
std::cout << s << std::endl;
}
int main()
{
F(STR("Hello " << 3 << " again"));
F(STR('C' << 2));
return 0;
}
Instead of using a macro and trickery, just use some existing library
solution, or define such yourself, e.g.
#include <iostream>
#include <string>
#include <sstream>
class Str
{
private:
std::ostringstream myStream;
Str( Str const& );
Str& operator=( Str const& );
public:
Str() {}
template< typename T >
Str& operator<<( T const& v )
{
myStream << v; return *this;
}
operator std::string() const
{
return myStream.str();
}
};
void f( std::string const& s)
{
std::cout << s << std::endl;
}
int main()
{
f( Str() << "Hello " << 3 << " again" );
f( Str() << 'C' << 2 );
}
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?