'if (x)' 'x' 是 class 的实例,而不是隐式转换?
How is 'if (x)' where 'x' is an instance of a class, not an implicit conversion?
根据cppreference.com,显式转换函数不能用于隐式转换。例如,他们有这个:
struct B
{
explicit B(int) { }
explicit B(int, int) { }
explicit operator bool() const { return true; }
};
int main()
{
...
if (b2) ; // OK: B::operator bool()
...
}
本来以为'if (b2)'是隐式转换,所以不能使用显式转换函数。那么什么是不允许的隐式转换的示例?
In the following contexts, the type bool
is expected and the
implicit conversion is performed if the declaration bool t(e);
is
well-formed (that is, an explicit conversion function such as explicit
T::operator bool() const; is considered). Such expression e is said to
be contextually converted to bool.
- the controlling expression of if, while, for;
- ...
来自 C++ 17 标准(7 个标准转换)
4 Certain language constructs require that an expression be converted
to a Boolean value. An expression e appearing in such a context is
said to be contextually converted to bool and is well-formed if and
only if the declaration bool t(e); is well-formed, for some invented
temporary variable t (11.6).
声明
bool t( b2 );
格式正确,因为使用了直接初始化。
根据cppreference.com,显式转换函数不能用于隐式转换。例如,他们有这个:
struct B
{
explicit B(int) { }
explicit B(int, int) { }
explicit operator bool() const { return true; }
};
int main()
{
...
if (b2) ; // OK: B::operator bool()
...
}
本来以为'if (b2)'是隐式转换,所以不能使用显式转换函数。那么什么是不允许的隐式转换的示例?
In the following contexts, the type
bool
is expected and the implicit conversion is performed if the declarationbool t(e);
is well-formed (that is, an explicit conversion function such as explicit T::operator bool() const; is considered). Such expression e is said to be contextually converted to bool.
- the controlling expression of if, while, for;
- ...
来自 C++ 17 标准(7 个标准转换)
4 Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (11.6).
声明
bool t( b2 );
格式正确,因为使用了直接初始化。