Lambda捕获作为const引用? [英] Lambda capture as const reference?

查看:234
本文介绍了Lambda捕获作为const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我希望下面标记的赋值失败,例如:

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

#include <cstdlib>
#include <vector>
#include <string>
#include <algorithm>
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引用捕获一个非const对象? ( 2015年8月

推荐答案

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.

这篇关于Lambda捕获作为const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆