C ++最烦人的解析是何时使用数字文字作为参数? [英] C++ Most vexing parse when a number literal is the argument?

查看:57
本文介绍了C ++最烦人的解析是何时使用数字文字作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was making a class that looked like this:

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

出现错误,我知道这是因为编译器将此解释为函数而不是构造函数参数.但是我想知道当我在这种情况下在括号中传递数字文字时,是否有任何歧义?我知道我可以通过在此处使用大括号来解决此问题,但是我本来以为不会出现最令人头疼的解析问题,因为使用256的数字常量不能解释为函数.

It came up with an error, and I know this is because the compiler interprets this as a function instead of a constructor argument. But I was wondering is there anything ambiguous when I've passed a number literal in brackets such as in this case? I know I can fix this by just using curly brackets here, 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.

很高兴关闭或删除此问题.我了解到的是,即使该特定的行不是模棱两可的,C ++ 11的一般规则也禁止使用=或{}以外的任何东西进行类内初始化程序,这是一个一般规则,以便不具有该规则的额外例外.另一方面,在main()函数中创建矢量为:

I'm happy to close or delete this question. The thing I learned is that even though that particular line isn't ambiguous, the general rules of C++11 forbid in-class initialisers with anything other than = or {}, this is as a general rule so as not to have an extra exception to the rule. On the other hand creating the vector in the main() function as:

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

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

Works fine. It's not an ambiguous expression, apparently.

推荐答案

但是我本来以为不会出现最烦人的解析问题,因为使用256的数字常量不能被解释为函数.

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中正式处理的] :

That is correct, it is not the most vexing parse. The most vexing parse is formally handled in [dcl.ambig.res]:

在[stmt.ambig]中提到的函数样式转换和声明之间的相似性也可能引起歧义.在这种情况下,选择是在带有围绕参数名称的一对多余括号的函数声明和以函数样式作为初始值设定项的对象声明之间进行选择.就像[stmt.ambig]中提到的歧义一样,解决方案是考虑可能是声明的任何构造.

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.

这里要注意的是,您不能使用()初始化成员,只能使用 = {} 初始化成员,因此自然地,歧义解决方案不会申请.

The catch here is that you cannot initialize members using (), only = or {}, so naturally the ambiguity resolution does not apply.

这篇关于C ++最烦人的解析是何时使用数字文字作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆