将lambda作为函数指针传递,可以正常使用gcc 4.6.3:
#example adapt from LoudNPossiblyWrong http://stackoverflow.com/questions/3351280/c0x-lambda-to-function-pointer-in-vs-2010
#include <iostream>
using namespace std;
void func(int i){cout << "I'V BEEN CALLED: " << i <<endl;}
void fptrfunc(void (*fptr)(int i), int j){fptr(j);}
int main(){
fptrfunc(func,10); //this is ok
fptrfunc([](int i){cout << "LAMBDA CALL " << i << endl; }, 20); //works fine
return 0;
}
但是传递lambda作为参考将不起作用:
#example adapt from LoudNPossiblyWrong http://stackoverflow.com/questions/3351280/c0x-lambda-to-function-pointer-in-vs-2010
#include <iostream>
using namespace std;
void func(int i){cout << "I'V BEEN CALLED: " << i <<endl;}
void freffunc(void (&fptr)(int i), int j){fptr(j);}
int main(){
freffunc(func,10); //this is ok
freffunc([](int i){cout << "LAMBDA CALL " << i << endl; }, 20); //DOES NOT COMPILE
return 0;
}
错误:从‘void (&)(int)’
类型的右值
‘<lambda(int)>’
类型的非const引用无效
任何人都能解释为什么会这样吗?
答案 0 :(得分:1)
lambda实际上不是一个函数,它是一个闭包对象。基本上,定义了operator()
的编译器生成的类。非捕获闭包还定义了一个转换运算符,用于转换为良好的旧指针到函数。