[英]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.