简体   繁体   中英

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:

error: expected ',' before '(' token

but the declaration of iter2 is OK.

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)] . Even without the parentheses, you cannot capture a single member variable like that. You need to use C++14's capture inits:

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

Or alternatively, following your second lambda, capture just target :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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