Lambda capture as const reference?(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 捕获作为常量引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Lambda 捕获作为常量引用?


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01