使用 GCC 7.3.0 时发生代码转换错误

Code converting error occurs using GCC 7.3.0

本文关键字:代码 转换 错误 GCC 使用      更新时间:2023-10-16

使用 GCC 7.3.0 时发生位移错误

In file included from show_factory.h:21:0,
                 from show.h:21,
                 from main.cpp:27:
common.h: In member function ‘bool tfs::tools::ServerInfo::operator<<(std::ostream&) const’:
common.h:173:22: error: cannot convert ‘std::basic_ostream<char>::__ostream_type {aka std::basic_ostream<char>}’ to ‘bool’ in return
         return os << server_id_;
                      ^~~~~~~~~~
Makefile:630: recipe for target 'main.o' failed

如何更改此处的代码以使其安全无恙?

在 GCC 的旧版本 (<=5) 中,这应该编译得很好(根据他们的 repo https://github.com/yage99/tfs)。它是GCC 7.3.0的新功能吗?

std::ostream 自 C++11 以来标记为explicit boolreturn语句中不考虑显式转换;您需要显式强制转换。


作为旁注:用于插入流operator<<重载的返回类型传统上是std::ostream& 。 这允许链接插入,例如 std::cout << foo << bar 。 您的operator<<重载通常也应该是一个自由函数,而不是一个成员。 成员不允许使用标准stream << object语法。