将 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)>’
类型的右值
谁能解释一下这是为什么?
最佳答案
lambda 并不是一个真正的函数,它是一个闭包对象。基本上,一个编译器生成的类,定义了operator()
。非捕获闭包还定义了一个转换运算符,用于转换为良好的旧指针函数。
关于c++ - 无法将 lambda 函数作为函数引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16750624/