【问题标题】:Explicit and implicit conversion显式和隐式转换
【发布时间】:2017-09-19 09:15:27
【问题描述】:

我很惊讶这个 struct,它只能显式转换为 bool,在 if 语句中工作正常:

struct A
{
    explicit operator bool(  ) const
    {
        return m_i % 2 == 0;
    }

    int m_i;
};

int main()
{
    A a{ 10 };

    if ( a ) // this is considered explicit
    {
        bool b = a; // this is considered implicit 
                    // and therefore does not compile           
    }        
    return 0;
}

为什么会这样? C++ 标准背后的设计原因是什么? 我个人发现第二次转换比第一次更明确。为了更清楚,我希望编译器在这两种情况下都强制具有以下内容:

int main()
{
    A a{ 10 };

    if ( (bool)a )
    {
        bool b = (bool)a;
    }        
    return 0;
}

【问题讨论】:

标签: c++11 type-conversion implicit-conversion explicit explicit-conversion


【解决方案1】:

§6.4 选择语句 [stmt.select]

  1. 作为表达式的条件的值是表达式的值,根据上下文转换为 bool,用于 switch 以外的语句;

§4 标准转换 [conv]

某些语言结构要求将表达式转换为 一个布尔值。说出现在这种上下文中的表达式 e 被 上下文转换为 bool 并且当且仅当 如果声明 bool t(e); 格式正确,对于某些人来说 临时变量 t (8.5)。

所以if 中的条件表达式必须在上下文中可转换为bool,这意味着允许显式转换。

这是最有可能完成的模式,因为if 的条件只能评估为布尔值,所以通过说if(cond),您明确声明您希望cond 被评估为一个布尔值。

【讨论】:

  • 谢谢,我以前从未听说过contextually convertible 的概念。您能否补充一下您的答案,在哪些情况下转换操作被认为是上下文相关的?
  • @nyarlathotep108 作为if while for 语句的条件。除此之外,我必须扫描整个标准。并且超出了问题的范围。
  • @nyarlathotep108 在快速扫描中发现:逻辑否定运算符 (!op) 的操作数、逻辑运算符的操作数 (例如 op1 && op2)、条件运算符 ? : 上的断言static_assert,除了说明符之外没有。
猜你喜欢
  • 1970-01-01
  • 2014-11-15
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
相关资源
最近更新 更多