【发布时间】:2017-09-21 05:51:41
【问题描述】:
对不起,我不知道该如何命名这个问题。
我在 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...){} "catch" 它,我会收到一条错误消息,告诉我 lambda我解析成LoopPixels 是错误的类型。
错误信息:
没有合适的转换函数来自“lambda []void (uchar &r, uchar &g, uchar &b)->void" 到 "void (*)(uchar &r, uchar &g, uchar &b)" 存在
如何访问已被解析为函数参数的 lambda 中的变量?
【问题讨论】:
-
只有不捕获任何内容的 lambda 才能转换为函数指针。将您的函数更改为模板,并将函数指针更改为模板参数。
-
好的,我已将我的函数更改为
template <class T> void LoopPixels(cv::Mat &img, T *fptr),我得到Couldn't match type 'T*' against <lambda> -
你传递一个 lambda,而不是一个指针。因此出现错误消息。
-
“将 lambda 作为参数。”。不,您的函数采用函数指针(并且无捕获 lambda 可以转换为该指针)。