c++ - 为什么这个 Github 项目将字符串转换为 bool 值?

标签 c++ type-conversion implicit-conversion

这是 Github 上一个非常流行的生物信息学 C++ 项目:

https://github.com/jts/sga/blob/master/src/Util/ClusterReader.cpp

有一行:

bool good = getline(*m_pReader, line);

我不能编译这一行,我不知道作者为什么要那样做。

根据documentation , getline 返回一个非 bool 的字符串。事实上,这就是我在尝试编译项目时得到的结果:

ClusterReader.cpp: In member function ‘bool 
ClusterReader::readCluster(ClusterRecord&)’:
ClusterReader.cpp:70:41: error: cannot convert ‘std::basic_istream<char>’ to ‘bool’ in initialization
 bool good = getline(*m_pReader, line);

为什么 C++ 代码将字符串转换为 bool 值?这怎么可能?

最佳答案

std::getline不返回 std::string,而是返回 std::basic_istream。对于 getline(*m_pReader, line);,它只返回 *m_pReader

std::basic_istream 可以通过 std::basic_ios::operator bool 隐式转换为 bool (自 C++11 起),

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

在 C++11 之前,它可以隐式转换为 void*,也可以转换为 bool

您的编译器似乎未能执行隐式转换,您可以使用 !fail() 作为解决方法,例如

bool good = !getline(*m_pReader, line).fail();

关于c++ - 为什么这个 Github 项目将字符串转换为 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43775495/

相关文章:

c++ - GStreamer 中的自定义分配器

c++ - 如何修复 “error: invalid use of non-static data member '树::root'” error in c++?

c++ - 将 win32 控制台应用程序切换到图形模式

c++ - 实现类似 OpenGl 的 MIRRORED_REPEAT

python - 将包含字符串和整数值的元组中的值组合起来并存储为数据帧

Go:使用乘数将 float64 转换为 int

c# - 为什么下面的代码编译执行成功了?

java - 在 Java 中将整数数组的元素转换为单个整数

c# - 你能用隐式转换满足通用约束吗?

javascript - 在 Javascript 中将字符串转换为负 float