我想捕捉一個「參考」的拉姆達,我認爲,一個函數指針會做的伎倆,如:如何創建一個lambda的「引用」?
int (*factorial)(int) = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
,但我得到cannot convert from main::lambda<......> to int(_cdecl *)(int)
。
指向lambda的正確方法是什麼?
我想捕捉一個「參考」的拉姆達,我認爲,一個函數指針會做的伎倆,如:如何創建一個lambda的「引用」?
int (*factorial)(int) = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
,但我得到cannot convert from main::lambda<......> to int(_cdecl *)(int)
。
指向lambda的正確方法是什麼?
由於lambda不是無狀態的,所以它不能轉換爲函數指針。改爲使用std::function
。
std::function<int(int)> factorial = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
與「原始」lambda相比,這具有不重要的間接費用,作爲警告。每次調用大致相當於調用一個'虛擬'方法。這並不是什麼壞事,但與通話中所做的工作相比,意義重大。 – Yakk
@Yakk是的,你支付'std :: function'類型擦除的代價;我只是從幾個星期前尋找這個答案鏈接到:) – Praetorian
這是什麼意思'不是無狀態?此外,@Yakk什麼是間接費用? – sircodesalot
這將是最接近你有什麼已經:
std::function<int (int)> factorial = [&](int x){
return (x < 2)
? 1
: x * factorial(x - 1);
};
通常你也可以使用auto
,但在這種情況下,它不起作用,因爲該功能是遞歸的。
'auto'不起作用,請參閱鏈接的問題。 –
@JesseGood:很好 - 謝謝。 –
您已經有了很好的答案。以下只是一個好奇心,但我不會建議你使用它。
正如別人所說的答案,lambda factorial
試圖捕捉自己,因此它不是無狀態的。因此,它不能轉換爲函數指針。
Lambda表達式不需要捕捉全球或static
對象,因此,如果你讓factorial
全局或static
變量,那麼你並不需要捕捉它,並能正常工作(GCC 4.7.2)
#include <iostream>
typedef int (*function)(int);
int main() {
static function factorial = [](int x){
return (x < 2) ? 1 : x * factorial(x - 1);
};
std::cout << factorial(5) << '\n';
}
您還可以創建一個工廠是這樣的:
#include <iostream>
typedef int (*function)(int);
function make_factorial() {
static function factorial = [](int x){
return (x < 2) ? 1 : x * factorial(x - 1);
};
return factorial;
}
int main() {
auto factorial = make_factorial();
std::cout << factorial(5) << '\n';
}
如果你想混淆甚至更多:-)然後消除typedef
:
// This is a function returning a pointer to a function taking an int and returning an int.
int (*(make_factorial)())(int) {
static int (*factorial)(int) = [](int x){
return (x < 2) ? 1 : x * factorial(x - 1);
};
return factorial;
}
如果lambda沒有捕獲任何東西,它可以轉換爲函數指針。 – jrok
很酷,你說得對。很高興知道,謝謝。 – sircodesalot
這幾乎是http://stackoverflow.com/questions/2067988/recursive-lambda-functions-in-c0x – doctorlove