c++ - 为什么要在 if 条件下进行解析?

标签 c++ c++11 most-vexing-parse

<分区>

考虑代码:

#include <iostream>

struct Foo
{
    Foo(int){}
    operator bool() const
    {
        return true;
    }
};

int main()
{
    if(Foo foo{42})
    {
        std::cout << "ok\n";
    }
}

它在 gcc5 下编译良好。但是,如果我将行 if(Foo foo{42}) 替换为

if(Foo foo(42))

我得到一个编译时错误:

error: expected primary-expression before 'foo'

这是怎么回事?没有令人烦恼的解析 imo,那么为什么使用大括号有效?

最佳答案

条件 的语法不包括经典构造函数调用。

C++11 §6.4/1:

condition:
    expression
    attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
    attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

这用于 ifswitchwhiledo。现在我很惊讶地发现它用于 switch。我从没想过这是一个条件。

关于c++ - 为什么要在 if 条件下进行解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411163/

相关文章:

c++ - 将 vector 末尾的删除优化为调整大小

c++ - QWaitCondition : Destroyed while threads are still waiting

c++ - QT:将签名中具有基本类型的信号连接到签名中具有 QVariant 的插槽

c++ - 仅当模板参数不是 const 时才定义 C++ 转换运算符

c++11 - 如何使用 Eigen 的逐元素整数幂

c++ - 使用 () 或不使用创建对象的区别

c++ - 变量没有类类型,即使它已被定义

c++ - 默认构造函数的好奇心

c++ - 在 C++ 中的类中定义结构

c++ - 强制强类型枚举参与模板重载决策