我不知道这个问题的标题是什么,对不起。
我在C ++中有一个函数,它将lambda作为参数。
void LoopPixels(cv::Mat &img, void(*fptr)(uchar &r, uchar &g, uchar &b)) {
// ...
fptr(r, g, b); // Call the lambda function
}
然后我尝试调用此LoopPixels
函数。
int threshold = 50;
LoopPixels(img, [](uchar &r, uchar &g, uchar &b) {
r *= (uchar)threshold; // Unable to access threshold :(
});
我的问题是,我无法从lambda函数内部访问threshold
变量,如果我尝试使用[&threshold](uchar &r...){}
“捕获”,我收到错误告诉我,我解析为LoopPixels
的lambda是错误的类型。
错误讯息:
没有合适的转换函数来自“lambda [] void(uchar& r,uchar & g,uchar& b) - > void“to”void(*)(uchar& r,uchar& g,uchar& b)“ 存在
如何在lambda中访问已被解析为函数参数的变量?
答案 0 :(得分:5)
您无法将捕获lambda传递给函数指针。您必须更改函数以使用,或使用函数模板。
void LoopPixels1(cv::Mat &img, std::function<void(uchar &r, uchar &g, uchar &b)> fn);
// Or:
template<typename Callable>
void LoopPixels2(cv::Mat &img, Callable fn);
// Can be called with a capturing lambda
LoopPixels1(img, [threshold](uchar &r, uchar &g, uchar &b) { });
LoopPixels2(img, [threshold](uchar &r, uchar &g, uchar &b) { });
答案 1 :(得分:0)
你可以尝试使用它:
void LoopPixels(cv::Mat& img, uint& r, uint& g, uint& b, const std::function<void(uint& r, uint& g, uint& b)>& callback)
{
callback(r, g, b);
}
cv::Mat img;
int threshold = 50;
uint r = 1;
uint g = 1;
uint b = 1;
std::cout << "(before) rgb : " << r << g << b << std::endl;
LoopPixels(img, r, g, b, [threshold](uint& r, uint& g, uint& b)
{
r *= threshold;
g *= threshold;
b *= threshold;
});
std::cout << "(after) rgb : " << r << g << b << std::endl;
lamba捕获按值传递,因为在回调调用之前引用可能超出范围。
(我使用uint表示r,g,b变量而不是uchar,因为为一个int乘以uchar可能无法得到你期望的结果。)