I have a compiler error with Visual Studio 2013 (while Xcode 6.2 compiles) which I can't make any sense of:
following example code is an abstract, reduced excerpt from a format conversion:
#include<sstream>
void main(...){
(std::ostringstream()<<0).str();
}
while following version compiles:
#include<sstream>
void main(...){
(std::ostringstream()).str();
}
context:
std::string result=(std::ostringstream()<<value).str();
what do I miss here? Thanks!
The error message is error C2039: 'str': is not a member of 'std::basic_ostream<char,std::char_traits<char>>'
. It's complaining that str
is missing in std::basic_ostream<char,std::char_traits<char>>
aka std::ostream
, not std::ostringstream
.
std::ostringstream
's operator<<
still returns std::ostream&
(it inherits these operators from std::ostream
), which has no str()
member.
Clang/libc++ (which is what Xcode uses) implements an extension in its rvalue stream insertion operator that
operator<<
s, andstd::ostream&
.Together this made your code compile in Xcode.
To call .str()
, you can manually static_cast
(std::ostringstream()<<value)
back to std::ostringstream&
(use either std::ostringstream &&
or const std::ostringstream&
for libc++ compatibility, since its rvalue stream insertion operator returns an rvalue reference to the stream).