是否可以通过 const
lambda 表达式中的引用来捕获?
我希望下面标记的作业失败,例如:
#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 月_)
原文由 John Dibling 发布,翻译遵循 CC BY-SA 4.0 许可协议
const
不在 n3092 的捕获语法中:文本只提到了按拷贝捕获和按引用捕获,并没有提到任何类型的 const-ness。
对我来说感觉像是一个疏忽,但我并没有非常密切地关注标准化过程。