I was trying to come up with a smart way to combine various things into one string argument for a function, without using explicitly ostringstream . I thought:
#define OSS(...) \ dynamic_cast<std::ostringstream const&>(std::ostringstream() << __VA_ARGS__).str()
However, given:
void f( string const &s ) { cout << s << endl; } int main() { char const *const s = "hello"; f( OSS( '{' << s << '}' ) ); ostringstream oss; oss << '{' << s << '}'; cout << oss.str() << endl; }
it prints at startup:
123hello} {hello}
where 123 is the ASCII code for } . Why is using a macro wrong?
FYI: I am currently using g ++ 4.2.1 on Mac OS X as part of Xcode 3.x.
Solution now i'm using
class string_builder { public: template<typename T> string_builder& operator,( T const &t ) { oss_ << t; return *this; } operator std::string() const { return oss_.str(); } private: std::ostringstream oss_; }; #define BUILD_STRING(...) (string_builder(), __VA_ARGS__) using namespace std; void f( string const &s ) { cout << s << endl; } int main() { char const *const s = "hello"; f( BUILD_STRING( '{', s, '}' ) ); }
source share