2017-09-21 75 views
1

我不知道該怎麼稱呼這個問題,抱歉。lambda函數中的「Capture」變量被解析爲參數


我在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是拉姆達錯誤的類型。

錯誤消息:

從沒有合適的轉換函數 「拉姆達[]空隙(UCHAR & R,UCHAR &克,UCHAR & B) - >空隙」 到「無效(*)(UCHAR & R,UCHAR &克,UCHAR &二)」 存在

如何我已經解析爲福拉姆達內訪問變量nction的論點?

+0

只捕獲任何東西的lambda表達式可以轉換爲函數指針。將您的函數更改爲模板,並將函數指針更改爲模板參數。 – rustyx

+0

好吧,我改功能 '模板 無效LoopPixels(CV ::墊與IMG,T * FPTR)' 和我得到'不能匹配型 'T *' 對' – Acidic

+0

你傳遞一個lambda,而不是一個指針。因此錯誤消息。 –

回答

4

您無法將捕獲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) { }); 
+0

您能否提供一個我可以怎樣稱呼'LoopPixels'的例子。 – Acidic

+1

值得一提:第一個選項,不要忘記包含標題'' – Christophe

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; 

的蘭巴捕獲是按值傳遞,因爲基準可以走出去的範圍回調調用之前。我使用uint代替了uchar的r,g,b變量,因爲乘以一個int的uchar可能不會給出你期望的結果。