存储lambda函数,将作用域变量作为类成员进行重用 [英] Store lambda function that captures the scope variable as a class member to reuse
本文介绍了存储lambda函数,将作用域变量作为类成员进行重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的类很多方法有这样的代码片段:
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;});
因此,我想存储lambda函数来重用它。但它从范围捕获 str
。
Therefore, I want to store the lambda function to reuse it. But it captures the str
from the scope. How I should do that?
推荐答案
如果我理解它的话...
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;
}
};
用法:
std::string str = getSomeStr();
auto it = std::find_if(
vec.begin(),
vec.end(),
MyOperation(str));
您不必使用 str
temporary,或者使 MyOperation
只保存一个 std :: string
引用。
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.
当然,你可以这么做:
auto myOperation(std::string s) {
return [&s](const std::string& b) {
return s + "abc" == b;
};
}
但我没有看到这一点,坦率地说。
But I don't see the point, frankly.
这篇关于存储lambda函数,将作用域变量作为类成员进行重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文