不能通过lambda函数作为函数引用? [英] Cannot pass lambda function as function reference?

查看:133
本文介绍了不能通过lambda函数作为函数引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递lambda作为函数指针可以很好地与gcc 4.6.3:

Passing the lambda as function pointer works fine with 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作为引用不起作用:

However passing the lambda as reference will not work:

#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;
}

错误:类型

任何人都可以解释为什么?

Can anyone explain why is that?

推荐答案

,它是一个闭包对象。基本上,一个编译器生成的类与 operator()定义。非捕获闭包还定义了一个转换操作符,用于转换为旧的指针到函数。

A lambda is not really a function, it's a closure object. Basically, a compiler-generated class with operator() defined. A non-capturing closure also defines a conversion operator for converting to good old pointer-to-function.

这篇关于不能通过lambda函数作为函数引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆