简体   繁体   English

无法通过引用捕获Lambda中的成员变量

[英]Can't capture a member variable in a lambda by reference

Consider the following code snippet: 考虑以下代码片段:

#include <map>
#include <string>
#include <set>
#include <algorithm>
#include <cmath>

using TargetsType = std::map<float, std::string>;
using TimesType = std::set<float>;

void foo (const TargetsType& targets,
          const TimesType& times)
{
    for (const auto& target : targets)
    {
        // fails to compile
        TimesType::const_iterator iter1 = std::find_if(times.begin(),
                                                       times.end(),
                                                       [&(target.first)](float item) 
                                                       {
                                                           return std::fabs(item - target.first) < 0.1f;
                                                       });

        // compiles OK
        TimesType::const_iterator iter2 = std::find_if(times.begin(),
                                                       times.end(),
                                                       [&](float item) 
                                                       {
                                                           return std::fabs(item - target.first) < 0.1f;
                                                       });
    }
}

The declaration of iter1 fails to compile with the following error: iter1的声明无法编译,并出现以下错误:

error: expected ',' before '(' token

but the declaration of iter2 is OK. 但是iter2的声明可以。

Can someone explain why the first declaration doesn't compile? 有人可以解释为什么第一个声明不编译吗?

[&(target.first)](float item) {
    return std::fabs(item - target.first) < 0.1f;
}

You can't do [&(target.first)] . 您不能执行[&(target.first)] Even without the parentheses, you cannot capture a single member variable like that. 即使没有括号,您也无法捕获这样的单个成员变量。 You need to use C++14's capture inits: 您需要使用C ++ 14的捕获init:

[&first = target.first](float item) {
    return std::fabs(item - first) < 0.1f;
}

Or alternatively, following your second lambda, capture just target : 或者,在第二个lambda之后,仅捕获target

[&target](float item) {
    return std::fabs(item - target.first) < 0.1f;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM