当数字文字是参数时,C++ 最令人烦恼的解析是什么?
C++ Most vexing parse when a number literal is the argument?
我正在制作一个 class,看起来像这样:
struct InputHandler
{
std::vector<std::pair<int, int>> keyBindings( 256 );
};
出现错误,我知道这是因为编译器将其解释为函数而不是构造函数参数。但是我想知道当我在括号中传递数字文字时是否有任何歧义,例如在这种情况下?我知道我可以通过在这里使用花括号来解决这个问题,但我认为最令人烦恼的解析问题不会出现,因为使用 256 的数字文字不能被解释为一个函数。
编辑:我很高兴关闭或删除这个问题。我学到的是,即使该特定行没有歧义,C++11 的一般规则禁止使用除 = 或 {} 之外的任何 in-class 初始化程序,这是一般规则,因此没有额外的例外规则。另一方面,在 main() 函数中创建向量为:
std::vector<std::pair<int, int> foo(5);
工作正常。这显然不是一个模棱两可的表达方式。
But I was wondering is there anything ambiguous when I've passed a number literal in brackets such as in this case?
可能不会,但这会使语法更复杂。默认成员初始化程序只支持统一初始化和复制初始化,因为这些东西不可能出现在现有代码中。将它们与函数声明区分开来很容易。
添加另一个 括号的重载用法从来都不是目标。 IMO,它被过度使用了。如果它一般不受支持,那么仅针对您想到的这个特定用例支持它几乎不是一个值得语法扭曲的有用功能。
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.
这里的问题是您不能使用 ()
初始化成员,只能使用 =
或 {}
,因此歧义解决方案自然不适用。
我正在制作一个 class,看起来像这样:
struct InputHandler
{
std::vector<std::pair<int, int>> keyBindings( 256 );
};
出现错误,我知道这是因为编译器将其解释为函数而不是构造函数参数。但是我想知道当我在括号中传递数字文字时是否有任何歧义,例如在这种情况下?我知道我可以通过在这里使用花括号来解决这个问题,但我认为最令人烦恼的解析问题不会出现,因为使用 256 的数字文字不能被解释为一个函数。
编辑:我很高兴关闭或删除这个问题。我学到的是,即使该特定行没有歧义,C++11 的一般规则禁止使用除 = 或 {} 之外的任何 in-class 初始化程序,这是一般规则,因此没有额外的例外规则。另一方面,在 main() 函数中创建向量为:
std::vector<std::pair<int, int> foo(5);
工作正常。这显然不是一个模棱两可的表达方式。
But I was wondering is there anything ambiguous when I've passed a number literal in brackets such as in this case?
可能不会,但这会使语法更复杂。默认成员初始化程序只支持统一初始化和复制初始化,因为这些东西不可能出现在现有代码中。将它们与函数声明区分开来很容易。
添加另一个 括号的重载用法从来都不是目标。 IMO,它被过度使用了。如果它一般不受支持,那么仅针对您想到的这个特定用例支持它几乎不是一个值得语法扭曲的有用功能。
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.
这里的问题是您不能使用 ()
初始化成员,只能使用 =
或 {}
,因此歧义解决方案自然不适用。