Error: variable quot;cannot be implicitly captured because no default capture mode has been specifiedquot;(错误:变量“无法隐式捕获,因为未指定默认捕获模式)
问题描述
我正在尝试遵循这个例子使用带有 remove_if 的 lambda.这是我的尝试:
I am trying to follow this example to use a lambda with remove_if. Here is my attempt:
int flagId = _ChildToRemove->getId();
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
[](Flag& device) {
return device.getId() == flagId;
});
m_FinalFlagsVec.erase(new_end, m_FinalFlagsVec.end());
但这无法编译:
error C3493: 'flagId' cannot be implicitly captured because no default capture mode has been specified
如何在 lambda 表达式中包含外部参数 flagId?
How can I include the outside parameter, flagId, in the lambda expression?
推荐答案
您必须指定要捕获的 flagId.这就是 [] 部分的用途.现在它没有捕获任何东西.您可以按值或按引用捕获(更多信息).类似的东西:
You must specify flagId to be captured. That is what the [] part is for. Right now it doesn't capture anything. You can capture (more info) by value or by reference. Something like:
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
[&flagId](Flag& device)
{ return device.getId() == flagId; });
通过引用捕获.如果你想通过 const 值捕获,你可以这样做:
Which captures by reference. If you want to capture by const value, you can do this:
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
[flagId](Flag& device)
{ return device.getId() == flagId; });
或者通过可变值:
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
[flagId](Flag& device) mutable
{ return device.getId() == flagId; });
遗憾的是,没有直接的方法可以通过常量引用进行捕获.我个人只会声明一个临时的 const ref 并通过 ref 捕获它:
Sadly there is no straightforward way to capture by const reference. I personally would just declare a temporary const ref and capture that by ref:
const auto& tmp = flagId;
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
[&tmp](Flag& device)
{ return device.getId() == tmp; }); //tmp is immutable
这篇关于错误:变量“无法隐式捕获,因为未指定默认捕获模式"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:错误:变量“无法隐式捕获,因为未指定默认捕获模式"
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
