Visual Studio:“str() 不是 std::ostringstream 的成员”

rak*_*eta 4 c++ stl std ostringstream visual-studio

我有一个 Visual Studio 2013 编译器错误(当 Xcode 6.2 编译时),我无法理解:

以下示例代码是格式转换的抽象、精简摘录:

#include<sstream>
void main(...){
    (std::ostringstream()<<0).str();
}
Run Code Online (Sandbox Code Playgroud)

在以下版本编译时:

#include<sstream>
void main(...){
    (std::ostringstream()).str();
}
Run Code Online (Sandbox Code Playgroud)

语境:

std::string result=(std::ostringstream()<<value).str(); 
Run Code Online (Sandbox Code Playgroud)

我在这里想念什么?谢谢!

T.C*_*.C. 5

错误信息是error C2039: 'str': is not a member of 'std::basic_ostream<char,std::char_traits<char>>'。抱怨strstd::basic_ostream<char,std::char_traits<char>>aka 中丢失std::ostream,而不是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

  1. Makes it a better match for rvalue streams compared to the inherited member operator<<s, and
  2. returns a reference to the stream as is, without conversion to std::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).