为什么这个 Github 项目将字符串转换为布尔值?

Why this Github project converts a string to bool?

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

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

有一行:

bool good = getline(*m_pReader, line);

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

根据documentationgetline returns 一个字符串不是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++ 代码将字符串转换为布尔值?怎么可能?

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

std::basic_istream 可以通过 std::basic_ios::operator bool (C++11 起),

隐式转换为 bool

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();

看到这个question

用户Loki Astari在他的回答中写道:

getline() actually returns a reference to the stream it was used on. When the stream is used in a boolean context this is converted into a unspecified type (C++03) that can be used in a boolean context. In C++11 this was updated and it is converted to bool.

这意味着您可能没有使用最新的编译器(C++03 或更好的 C++11)。如果您使用 g++gcc,请尝试在命令中添加 -std=c++11