gpt4 book ai didi

c++ - Lambda 捕获和具有相同名称的参数 - 谁会影响另一个? (clang vs gcc)

转载 作者:IT老高 更新时间:2023-10-28 11:34:17 24 4
gpt4 key购买 nike

auto foo = "You're using g++!";
auto compiler_detector = [foo](auto foo) { std::puts(foo); };
compiler_detector("You're using clang++!");
  • clang++ 3.6.0 和更新版本输出“你正在使用 clang++!” 并警告 捕获 foo 未被使用。

  • g++ 4.9.0 和更新版本输出“你正在使用 g++!” 并警告 参数 foo 未被使用。

这里哪个编译器更准确地遵循 C++ 标准?

wandbox example

最佳答案

更新:正如核心主席在底部报价中所 promise 的,代码是 now ill-formed :

If an identifier in a simple-capture appears as the declarator-id of a parameter of the lambda-declarator's parameter-declaration-clause, the program is ill-formed.


不久前在 lambdas 中存在一些关于名称查找的问题。它们由 N2927 解决:

The new wording no longer relies on lookup to remap uses of captured entities. It more clearly denies the interpretations that a lambda's compound-statement is processed in two passes or that any names in that compound-statement might resolve to a member of the closure type.

查找总是在 lambda-expression 的上下文中完成,而不是“在”转换为闭包类型的成员函数体之后。见 [expr.prim.lambda]/8 :

The lambda-expression's compound-statement yields the function-body ([dcl.fct.def]) of the function call operator, but for purposes of name lookup, […], the compound-statement is considered in the context of the lambda-expression. [ Example:

struct S1 {
int x, y;
int operator()(int);
void f() {
[=]()->int {
return operator()(this->x+y); // equivalent to: S1::operator()(this->x+(*this).y)
// and this has type S1*
};
}
};

end example ]

(该示例还清楚地表明,查找不会以某种方式考虑生成的闭包类型的捕获成员。)

名称 foo 未在捕获中(重新)声明;它在包含 lambda 表达式的 block 中声明。参数 foo 在嵌套在该外部 block 中的 block 中声明(参见 [basic.scope.block]/2 ,其中还明确提到了 lambda 参数)。查找顺序明显是from inner to outer blocks .因此应该选择参数,即Clang是对的。

如果您要将捕获设置为初始化捕获,即 foo = "" 而不是 foo,则答案将不清楚。这是因为现在捕获的实际上是induces a declaration没有给出其“ block ”。我给核心主席发了消息,他回复了

This is issue 2211 (a new issues list will appear on the open-std.org site shortly, unfortunately with just placeholders for a number of issues, of which this is one; I'm working hard to fill in those gaps before the Kona meeting at the end of the month). CWG discussed this during our January teleconference, and the direction is to make the program ill-formed if a capture name is also a parameter name.

关于c++ - Lambda 捕获和具有相同名称的参数 - 谁会影响另一个? (clang vs gcc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42088015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com