我不知道该怎么称呼这个问题,对不起.
我在C++中有一个函数,它将lambda作为参数.
void LoopPixels(cv::Mat &img, void(*fptr)(uchar &r, uchar &g, uchar &b)) {
// ...
fptr(r, g, b); // Call the lambda function
}
Run Code Online (Sandbox Code Playgroud)
然后我试着调用这个LoopPixels函数.
int threshold = 50;
LoopPixels(img, [](uchar &r, uchar &g, uchar &b) {
r *= (uchar)threshold; // Unable to access threshold :(
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,我无法threshold从lambda函数内部访问变量,如果我尝试"捕获"它[&threshold](uchar &r...){},我收到一个错误,告诉我我解析的lambda LoopPixels是错误的类型.
错误信息:
没有合适的转换函数来自"lambda [] void(uchar&r,uchar&g,uchar&b) - > void"to"void(*)(uchar&r,uchar&g,uchar&b)"存在
如何在lambda中访问已被解析为函数参数的变量?
您无法将捕获lambda传递给函数指针.您必须更改要使用的功能std::function,或使用功能模板.
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) { });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |