【问题标题】:Compilation fails because of Lambda function [duplicate]由于 Lambda 函数,编译失败 [重复]
【发布时间】:2016-10-08 21:25:41
【问题描述】:

Given 是一个模板函数,它检查存储在容器中的某些元素(由 numElems 指定)是否等于任何传递的元素 elems

template<typename MyType>
bool Container<MyType>::elemsEqual(const int & numElems, const std::initializer_list<MyType>& elems)
{
     for (int i = 0; i < numElems; i++) {
         const MyType& currElem = getElem(i);
             if (std::none_of(elems.begin(), elems.end(), [](MyType& elem) {return currElem == elem; })) {
                 return false;
             }       
     }
     return true;
}

编译中止并显示错误消息:

'currElem' 不能被隐式捕获,因为没有默认捕获 已指定模式

这里出了什么问题,我该如何解决这个问题?

【问题讨论】:

  • 因缺乏研究努力而被否决。至少在下次询问之前谷歌错误消息。

标签: c++ templates lambda


【解决方案1】:

您需要指定要如何捕获局部变量,或者按值(创建副本):

[=](MyType& elem)

或参考:

[&](MyType& elem)

【讨论】:

  • 谢谢! MyType 在我的情况下必须是 const,所以 [=](const MyType&amp; elem)[&amp;](const MyType&amp; elem) 是完全正确的。
猜你喜欢
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多