[英]C++11: Cannot capture `this` when trying to capture member of class in lambda function
我正在编写一个简单的测试,以了解如何将C ++ 11 Lambda用于最大程度的代码重用。 我有一个函数fill_vector()
,在一种情况下,我希望它简单地用随机数填充向量,但是在另一种情况下,我希望它也为我提供这些数字的最大值。
这是我到目前为止的内容:
#include <iostream>
#include <random>
#include <vector>
#include <algorithm>
#include <iterator>
template <class Function>
void fill_vector(std::vector<int> &v, Function side)
{
for(auto i=v.begin(); i!=v.end(); ++i)
{
*i = rand() % 100;
}
side.lambda(v);
}
class null_test
{
public:
constexpr static auto lambda = [] (std::vector<int> x) { };
};
class test
{
public:
test() : max(0) { }
int max;
static auto lambda = [=] (std::vector<int> x) { max =
std::max_element(x.begin(),x.end()); };
};
int main()
{
std::vector<int> v(20);
null_test n;
fill_vector(v,n);
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout," "));
std::cout << std::endl;
std::vector<int> v2(20);
test t;
fill_vector(v2,t);
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout," "));
std::cout << std::endl;
std::cout << t.max << std::endl;
return 0;
}
导致错误:此lambda函数未捕获“ this”,指向我在test
定义的lambda。 我已经尝试过各种捕获语句,但是似乎什么也无法工作。 我想念什么?
另外,是否有可能在fill_vector
循环中使用lambda,例如可以提取出每个第n个填充的元素? 我的目标是能够在较大的项目中尽可能多地重用诸如fill_vector
函数,以用于其他可能需要对其稍作fill_vector
函数。
看你的课堂test
:
class test
{
public:
int max;
static auto lambda = [=] (std::vector<int> x) {
max = std::max_element(x.begin(),x.end());
};
};
这里有几个问题:
operator()
是const
,并且您正在尝试修改成员。 mutable
,也不会发生任何事情。 std::max_element
返回一个迭代器,而不是实际的元素。 您要编写的lambda可能如下所示:
test t;
std::vector<int> v2(20);
fill_vector(v2, [&t](const std::vector<int>& x){
t.max = *std::max_element(x.begin(), x.end());
});
只需将fill_vector()
函数更改为可调用的即可,而不是具有可调用的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.