Lambda 捕获作为常量引用?

2023-06-30C/C++开发问题
4

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

问题描述

是否可以通过 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.

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6