Saturday, 15 September 2012

c++ - Trouble with std::ostringstream as function parameter -



c++ - Trouble with std::ostringstream as function parameter -

so got stuck on simple print-function today , don't know how prepare problem. want pass strings function in std::cout-style this:

foo(std::ostringstream() << "hello" << " world!");

and i've read should possible function along lines of

void foo(std::ostringstream& in)

but when implementing unusual behavior:

#include <iostream> #include <sstream> void foo(std::ostringstream& in) { std::cout << in.str(); } int main() { std::ostringstream working; working << "hello" << " world!"; foo(working); // ok std::ostringstream notworking; notworking << "hello"; foo(notworking<<" world!"); // not ok?! homecoming 0; }

while first phone call of foo seems fine , works expected, sec 1 refuses compile though should (from perspective) technically same thing.

error:

error c2664: 'void foo(std::ostringstream &)': cannot convert parameter 1 'std::basic_ostream<char,std::char_traits<char>>' 'std::ostringstream &'

i'm using ms visual studio 2013 express on win7 x64

the overloads of shifting operators io operations take base of operations streams reference. is:

std::ostream& operator<<( std::ostream& os , foo myfo ) { os << myfoo; homecoming os; }

so utilize std::ostream instead of std::ostringstream function parameter:

void f( std::ostream& stream );

c++ visual-c++ stringstream

No comments:

Post a Comment