Is it possible to use a temporary stringstream object?

It works:

stringstream temp; temp << i; result_stream << transform(temp.str()); 

( transform is a function that takes a string and returns a string ; i is int ). However, my attempt to allow C ++ 11 to create a temporary object without a name does not work:

 result_stream << transform((stringstream() << i).str()); 

I thought this would work, as the second << should just return the first argument, and I could use str() . But I get this error:

 error: 'class std::basic_ostream<char>' has no member named 'str' 

I am using g ++ 4.8.1 (MinGW-W64).

Is there a way to accomplish this (e.g. write such code using an unnamed temporary)? (The above code is a bit simplified, and the actual code involves using << for arguments other than int .)

+5
source share
4 answers

This does not work because the second << is std::ostream &operator<<(std::ostream &, int); , so the return type is ostream& , which does not have a str() member.

You will need to write:

 result_stream << transform( static_cast<stringstream &>(stringstream() << i).str() ); 
+6
source

The result of the << operator on a temporary stringstream is ostream . There ostream no str() method on ostream .

Use to_string :

 result_stream << transform(std::to_string(i)); 
+6
source

operator<<() returns a reference to the std::ostream base class contained in std::stringstream . The base class does not contain the str() method. You can drop it to std::stringstream& :

 result_stream << transform(static_cast<std::stringstream&>(std::stringstream() << i).str()); 
+4
source

Tried and could not do it for C ++ 11 (in 2009):

http://cplusplus.imtqy.com/LWG/lwg-active.html#1203

lib ++ went outside the law and implemented it anyway.

It is being revised, but cannot be standardized until 2017 (standardization is an ice process).

+4
source

Source: https://habr.com/ru/post/1208705/


All Articles