【发布时间】:2011-04-15 22:20:30
【问题描述】:
是否可以通过 lambda 表达式中的const 引用来捕获?
我希望下面标记的作业失败,例如:
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string strings[] =
{
"hello",
"world"
};
static const size_t num_strings = sizeof(strings)/sizeof(strings[0]);
string best_string = "foo";
for_each( &strings[0], &strings[num_strings], [&best_string](const string& s)
{
best_string = s; // this should fail
}
);
return 0;
}
更新: 由于这是一个老问题,如果 C++14 中有工具可以帮助解决这个问题,更新它可能会很好。 C++14 中的扩展是否允许我们通过 const 引用捕获非常量对象? (2015 年 8 月)
【问题讨论】:
-
你的 lambda 不应该像:
[&, &best_string](string const s) { ...}? -
捕获确实不一致。当你有一个应该访问但不能在 lambda 函数中修改的大型 const 对象时,“const &”会非常有用
-
查看代码。您可以使用两个参数 lambda 并将第二个参数绑定为 const 引用。不过是有代价的。
-
这在 C++11 中似乎是不可能的。但也许我们可以为 C++14 更新这个问题——是否有允许这样做的扩展? C++14 广义 lambda 捕获?