当我们在 C++ 中使用 "while" 时会发生什么转换?

What conversion happens when we use "while" in C++?

我正在使用 Microsoft documentation and cppreference 作为背景。微软的网站说,要在 while 中计算的表达式必须是整数类型、pointer 类型或与这些类型可转换的类型。 Cppreference 的网站虽然说 while 需要一个 bool 类型的表达式。

到底发生了什么?表达式是不是一定要转成bool?如果我在一段时间内使用,比如char类型的表达式,是不是一定要转成bool

例如根据 C++ 14 标准(6.4 选择语句)

2 The rules for conditions apply both to selection-statements and to the for and while statements

  1. ...The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed.

这是一个演示程序。

#include <iostream>

struct A
{
    operator int() const { return 1; };
};

int main() 
{
    A a;

    while ( a ) break;
    
    return 0;
}

首先使用用户定义的转换运算符

将对象a转换为类型int
operator int() const { return 1; };

之后应用了从类型 int 到类型 bool 的标准转换。

来自 C++ 14 标准(4 个标准转换)

7 [ Note: For class types, user-defined conversions are considered as well; see 12.3. In general, an implicit conversion sequence (13.3.3.1) consists of a standard conversion sequence followed by a user-defined conversion followed by another standard conversion sequence. — end note ]