【问题标题】:How is 'if (x)' where 'x' is an instance of a class, not an implicit conversion? [duplicate]'if (x)' 如何,其中'x' 是类的实例,而不是隐式转换? [复制]
【发布时间】:2022-01-17 07:51:30
【问题描述】:

根据 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)' 是隐式转换,因此无法使用显式转换函数。那么什么是不允许的隐式转换的例子呢?

【问题讨论】:

标签: c++ if-statement operator-overloading explicit-conversion


【解决方案1】:

Contextual conversions

在以下上下文中,类型 bool 是预期的,而 如果声明 bool t(e); 是,则执行隐式转换 格式良好(即显式转换函数,例如显式 T::operator bool() 常量;被认为)。这样的表达式 e 被称为 根据上下文转换为布尔值。

  • if、while、for 的控制表达式;
  • ...

【讨论】:

  • 啊,所以通过上下文转换,使它不隐式。我原以为两者是正交的。
【解决方案2】:

来自 C++ 17 标准(7 标准转换)

4 某些语言结构需要转换表达式 为布尔值。出现在这种上下文中的表达式 e 是 据说在上下文中转换为 bool 并且是格式良好的 if 和 仅当声明 bool t(e);是良构的,对于一些发明的 临时变量 t (11.6)。

声明

bool t( b2 );

格式正确,因为使用了直接初始化。

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2011-10-19
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多