为什么std::cin不能隐式转换为bool?

Why can std::cin not be implicitly converted to bool?

C++ Primer 5th Ed. 中,第 14 章讨论了转换运算符:

Under earlier versions of the standard, classes that wanted to define a conversion to bool faced a problem: Because bool is an arithmetic type, a class-type object that is converted to bool can be used in any context where an arithmetic type is expected.

Such conversions can happen in surprising ways. In particular, if istream had a conversion to bool, the following code would compile:

int i = 42;
cin << i; // this code would be legal if the conversion to bool were not explicit!

This program attempts to use the output operator on an input stream. There is no << defined for istream, so the code is almost surely in error. However, this code could use the bool conversion operator to convert cin to bool. The resulting bool value would then be promoted to int and used as the left-hand operand to the built-in version of the left-shift operator. The promoted bool value (either 1 or 0) would be shifted left 42 positions.

输入流可以转换为表示流内部状态(成功或失败)的 bool 值。我们曾经做过:

while(std::cin >> str)...

那为什么不能编译呢?

int x = 0;
std::cin << x;

如果我使用显式转换,它会起作用:

(bool)cin << 5; // works although bad

operator boolis declaredexplicit,所以不应该隐式转换为布尔值:

bool b = std::cin; // Error

因此您需要明确地将 cin 转换为布尔值才能工作:

bool b {std::cin}; // OK, explicitly converting

所以当你尝试调用

std::cin << 5;

它不会编译,因为您期望进行隐式转换,而 class 只允许显式转换。这是哪个作品:

bool(std::cin) << 5;

现在,为什么 while(std::cin >> x) 编译?标准保证在这种情况下显式转换为 bool。请参阅有关该问题的评论中链接的