Is it possible to pass in a stringstream and have the function write to it directly?
I remember I saw a function invoked similar to something like this:
my_func(ss << "text" << hex << 33);
Is it possible to pass in a stringstream and have the function write to it directly?
I remember I saw a function invoked similar to something like this:
my_func(ss << "text" << hex << 33);
Sure thing. Why wouldn't it be? Example declaration of such function:
void my_func(std::ostringstream& ss);
Absolutely! Make sure that you pass it by reference, not by value.
void my_func(ostream& stream) {
stream << "Hello!";
}
my_func
has to have a signature along the lines of:
void my_func( std::ostream& s );
, since that's the type of ss << "text" << hex << 33
. If the goal is
to extract the generated string, you'ld have to do something like:
void
my_func( std::ostream& s )
{
std::string data = dynamic_cast<std::ostringstream&>(s).str();
// ...
}
Note too that you can't use a temporary stream;
my_func( std::ostringstream() << "text" << hex << 33 );
won't compile (except maybe with VC++), since it's not legal C++. You could write something like:
my_func( std::ostringstream().flush() << "text" << hex << 33 );
if you wanted to use a temporary. But that's not very user friendly.
Yes it is, and
Function(expresion)
Will make the expression to be evaluated first and the result of it will be passed as a parameter
Note: Operator << for ostreams returns a ostream