gpt4 book ai didi

c++ - 推导 Lambda 捕获类型

转载 作者:可可西里 更新时间:2023-11-01 16:37:56 28 4
gpt4 key购买 nike

我最近发现,在 lambda 中按值捕获 const 对象意味着 labmda 主体(即 lambda 的数据成员)内的变量也是 const.
例如:

const int x = 0;
auto foo = [x]{
// x is const int
};

此行为在 draft for C++17 的 § 8.1.5.2 中提到。 :

For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the referenced type if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an anonymous union shall not be captured by copy.

我希望推断捕获变量的类型与推断自动相同。
是否有充分的理由为捕获的类型设置不同的类型推导规则?

最佳答案

在您的示例中,不可能修改 x,因为 lambda 不是 mutable,这使得函数调用运算符 const .但即使 lambda 是 mutable,引用的段落确实在 lambda const int 中创建了 x 的类型。

如果我没记错的话,这是 C++11 中的一个有意的设计决定,即在 lambda 中使用 x 的行为类似于在中使用 x封闭范围。也就是说,

void foo(int&);
void foo(const int&);
const int x = 0;
foo(x); // calls foo(const int&)
auto foo = [x]() mutable {
foo(x); // also calls foo(const int&)
};

这有助于避免错误,例如,某些代码从具有显式循环重写为使用 lambda 调用标准库算法。

如果我对这段记忆有误,希望有正确答案的人会介入并写下他们自己的答案。

关于c++ - 推导 Lambda 捕获类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811624/

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