我正在制作一个看起来像这样的类:
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.
这里的问题是您不能使用 ()
初始化成员,只能使用 =
或 {}
,所以歧义解决自然不会申请。