当数字文字是参数时,C++ 最令人烦恼的解析是什么?

标签 c++ ambiguous most-vexing-parse

<分区>

我正在制作一个看起来像这样的类:

struct InputHandler
{
    std::vector<std::pair<int, int>> keyBindings( 256 );
};

出现错误,我知道这是因为编译器将其解释为函数而不是构造函数参数。但是我想知道当我在括号中传递数字文字时是否有任何歧义,例如在这种情况下?我知道我可以通过在这里使用大括号来解决这个问题,但我认为最令人烦恼的解析问题不会出现,因为使用 256 的数字文字不能被解释为函数。

编辑:我很高兴关闭或删除这个问题。我学到的是,即使该特定行没有歧义,C++11 的一般规则禁止类内初始化器使用除 = 或 {} 以外的任何东西,这是一般规则,以免出现规则的额外异常(exception)。另一方面,在 main() 函数中创建 vector 为:

std::vector<std::pair<int, int> foo(5);

工作正常。显然,这不是一个模棱两可的表达。

最佳答案

but I would have thought the most vexing parse issue wouldn't arise as using a number literal of 256 couldn't be interpreted as a function.

没错,这不是最令人烦恼的解析。最令人头疼的解析在[dcl.ambig.res]中正式处理:

The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in [stmt.ambig] can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in [stmt.ambig], the resolution is to consider any construct that could possibly be a declaration a declaration.

这里的问题是您不能使用 () 初始化成员,只能使用 ={},所以歧义解决自然不会申请。

关于当数字文字是参数时,C++ 最令人烦恼的解析是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48048163/

相关文章:

c++ - 当我从 C++ 程序调用脚本时出现语法错误

c++ - QTcpSocket/QTcpServer内存管理/服务器崩溃

c++ - 模棱两可的重载运算符 C++20

java - 发送 ("test", 1.0d) 会产生 Java 8 编译错误、不明确的方法调用 xMethod(String,double...) 与 xMethod(String,Object...)

c++ - 函数定义还是变量定义?

c++ - 构造函数解释为函数调用,并奇怪地跳过了移动构造函数

c++ - I(I()) 的含义

c++ - 使用 C++/Qt 的上下文菜单

android - 在 C++ 中学习使用 ndk+opengl 开发游戏的资源?

swift - 模糊地使用backgroundColor swift