Lambda 捕获作为 const 参考?

新手上路,请多包涵

是否可以通过 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 许可协议

阅读 1.5k
2 个回答

const 不在 n3092 的捕获语法中:

 capture:
  identifier
  & identifier
  this

文本只提到了按拷贝捕获和按引用捕获,并没有提到任何类型的 const-ness。

对我来说感觉像是一个疏忽,但我并没有非常密切地关注标准化过程。

原文由 Steve M 发布,翻译遵循 CC BY-SA 2.5 许可协议

有一个更短的方法。

请注意,“best_string”之前没有与号。

它将是 const std::reference_wrapper<T> 类型。

 [best_string = std::cref(best_string)](const string& s)
{
    best_string = s; // fails
};

http://coliru.stacked-crooked.com/a/0e54d6f9441e6867

原文由 Sergey Palitsin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题