这是 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/