【发布时间】:2013-05-25 22:45:53
【问题描述】:
将 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;
}
错误:从 ‘<lambda(int)>’ 类型的右值初始化 ‘void (&)(int)’ 类型的非常量引用无效
谁能解释这是为什么?
【问题讨论】:
-
右值/临时不能绑定到非常量引用
-
尝试添加星号,例如
*[](int i){/*...*/}。不知道这是否有效...... -
@yngum,如果这是问题所在。我希望
void (&&fptr)(int i)能解决问题。但事实并非如此。 @Kerrek,这确实有效。也许这是因为@Angew 说,闭包对象有闭包=>指针的转换运算符,但没有闭包=>引用?