操纵器是否以某种方式转换流类型

Do Manipulators Convert the Stream Type Somehow?

本文关键字:方式 转换 类型 是否 操纵      更新时间:2023-10-16

>我正在尝试使用匿名ostringstream生成string : 使用匿名字符串流构造字符串

但是,当我使用操纵器时,我似乎无法再编译了:

const auto myString(static_cast<ostringstream>(ostringstream{} << setfill('!') << setw(13) << "lorem ipsum").str());

但即使在 gcc 5.1 中,这似乎也是不允许的:

prog.cpp: 在函数int main()中:
prog.cpp:8:109:错误:调用std::basic_ostringstream<char>::basic_ostringstream(std::basic_ostream<char>&)
没有匹配函数
const auto myString(static_cast<ostringstream>(ostringstream{} << setfill('!') << setw(13) << "lorem ipsum").str());

在/usr/include/c++/5/iomanip:45:0 包含的文件中,
来自 Prog.cpp:1:
/usr/include/c++/5/sstream:582:7:注意:候选
std::basic_ostringstream<_CharT, _Traits, _Alloc>::basic_ostringstream(std::basic_ostringstream<_CharT, _Traits, _Alloc>&&) [带_CharT = char ; _Traits = std::char_traits<char> ; _Alloc = std::allocator<char> ]

basic_ostringstream(basic_ostringstream&& __rhs)
/usr/include/c++/5/sstream:582:7:注意:参数 1 没有从 std::basic_ostream<char>std::basic_ostringstream<char>&&
的已知转换 /usr/include/c++/5/sstream:565:7: 注意: 候选人:
std::basic_ostringstream<_CharT, _Traits, _Alloc>::basic_ostringstream(const __string_type&, std::ios_base::openmode) [带_CharT = char ; _Traits = std::char_traits<char> ; _Alloc = std::allocator<char> ; std::basic_ostringstream<_CharT, _Traits, _Alloc>::__string_type = std::basic_string<char> ; std::ios_base::openmode = std::_Ios_Openmode ]

basic_ostringstream(const __string_type& __str,
/usr/include/c++/5/sstream:565:7:注意:参数 1 没有从 std::basic_ostream<char>const __string_type& {aka const std::basic_string<char>&}
的已知转换 /usr/include/c++/5/sstream:547:7: 注意: 候选:
std::basic_ostringstream<_CharT, _Traits, _Alloc>::basic_ostringstream(std::ios_base::openmode) [带_CharT = char ; _Traits = std::char_traits<char> ; _Alloc = std::allocator<char> ; std::ios_base::openmode = std::_Ios_Openmode ]

basic_ostringstream(ios_base::openmode __mode = ios_base::out)
/usr/include/c++/5/sstream:547:7:注意:参数 1 没有从 std::basic_ostream<char>std::ios_base::openmode {aka std::_Ios_Openmode}
的已知转换

这是另一个 gcc 流错误,还是我正在做的事情实际上是非法的?

static_cast<ostringstream>(...)

这将尝试从参数中的参数构造一个新的ostringstream,一个std::ostream&,没有std::ostringstream的构造函数。

您只想将引用转换回原始类型。将演员转换为参考:

static_cast<ostringstream&>(...)

然后它工作正常。

我不知道你认为什么有效,但是省略参考并移除机械手,它仍然失败。