no member named 'str' in 'std::basic_ostream<char>' with gcc and clang, but no problem with msvc

你说的曾经没有我的故事 提交于 2021-01-27 06:35:46

问题


This code snippet (https://gcc.godbolt.org/z/hKDMxm):

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    auto s = (ostringstream{} << "string").str();
    cout << s;
    return 0; 
}

compiles and runs as expected with msvc, but fails to compile with clang 9.0.0 and gcc 9.2 giving this error message:no member named 'str' in 'std::basic_ostream<char>'. Looking at https://en.cppreference.com/w/cpp/io/basic_ostringstream/str there is clearly str() member of ostringstream. Why clang and gcc are failing to compile this code?


回答1:


there is clearly str() member of ostringstream

Yes, but according to cppreference this overload of << should return a reference to basic_ostream<...> rather than ostringstream.

libstdc++ (GCC's standard library) does exactly this, while libc++ (Clang's standard library) and MSVC's standard library behave incorrectly here, technically.

However, it seems there is an open defect report suggesting that the overload of << that works with rvalue streams should return the exact stream type that was passed to it. If it gets accepted, your code will be valid.




回答2:


operator<< is member of std::ostream, and returns std::ostream& as described here

MSVC obviously has own overload this operator for std::ostringstream, what is not in standard



来源:https://stackoverflow.com/questions/59473325/no-member-named-str-in-stdbasic-ostreamchar-with-gcc-and-clang-but-no-p

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!