错误:变量“不能被隐式捕获,因为没有指定默认捕获模式” [英] Error: variable "cannot be implicitly captured because no default capture mode has been specified"
问题描述
我想要关注此示例使用 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
b $ b
如何在lambda表达式中包含外部参数 flagId
?
推荐答案
您必须指定要捕获的 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引用。我个人只是声明一个临时const引用和捕获通过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
这篇关于错误:变量“不能被隐式捕获,因为没有指定默认捕获模式”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!