Lambda 捕获作为常量引用?

2021-12-23 00:00:00 lambda c++ c++11 c++14

是否可以通过 lambda 表达式中的 const 引用来捕获?

Is it possible to capture by const reference in a lambda expression?

我希望下面标记的作业失败,例如:

I want the assignment marked below to fail, for example:

#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 中的扩展是否允许我们通过常量引用捕获非常量对象?(2015 年 8 月)

Update: As this is an old question, it might be good to update it if there are facilities in C++14 to help with this. Do the extensions in C++14 allow us to capture a non-const object by const reference? (August 2015)

推荐答案

const 不在 n3092 中捕获的语法中:

const isn't in the grammar for captures as of n3092:

capture:
  identifier
  & identifier
  this

文本仅提及按复制捕获和按引用捕获,并未提及任何类型的常量.

The text only mention capture-by-copy and capture-by-reference and doesn't mention any sort of const-ness.

对我来说感觉像是疏忽,但我并没有非常密切地遵循标准化流程.

Feels like an oversight to me, but I haven't followed the standardization process very closely.

相关文章