Store lambda function that captures the scope vari

2019-07-21 03:37发布

问题:

In my class lots of methods have such a snippet:

std::string str = getSomeStr();

auto it = std::find_if(
vec.begin(), 
vec.end(), 
[str](const std::string& b){return str + "abc" == b;});

Therefore, I want to store the lambda function to reuse it. But it captures the str from the scope. How I should do that?

回答1:

If I understood it right...

class MyOperation {
    std::string s;
public:
    MyOperation(std::string s) : s(s) { }

    operator()(const std::string& b) {
        return s + "abc" == b;
    }
};

Usage:

std::string str = getSomeStr();

auto it = std::find_if(
    vec.begin(), 
    vec.end(), 
    MyOperation(str));

You don't have to use the str temporary, or make MyOperation hold only a std::string reference. This depends on what do you want to achieve.


of course technically you can do this:

auto myOperation(std::string s) { 
    return [&s](const std::string& b) {
        return s + "abc" == b;
    };
}

But I don't see the point, frankly.



回答2:

How about a capture by reference and then assign to that reference before each use:

std::string str = getSomeStr();
std::string str2 = getSomeOtherStr();
std::string *captured_str;

auto lambda =  [&captured_str](const std::string* b){return *str + "abc" == b;}

captured_str = &str;
auto it = std::find_if(vec.begin(), vec.end(), lambda);
captured_str = &str2;
auto it = std::find_if(vec.begin(), vec.end(), lambda);


标签: c++ lambda