c++ - 无法将 lambda 函数作为函数引用传递?

标签 c++ c++11

将 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/

相关文章:

C++11 - std::function、模板和函数对象、奇怪的问题

c++ - Visual Studio "The debug worker process exited unexpectedly"每次运行都在同一个断点上

c++ - NDK 问题 : crash on 32bit, 在 64 位上不一致

c++ - 在 std::cout 刷新事件上捕获和引发事件

c++ - 在嵌套 lambda 的情况下如何初始化 lambda 捕获?

代码块中的 C++11 编译问题

c++ - 使用 VS2010 SP1 的函数模板中的编译器错误

c++ - 如何使用ShellExecuteEx在windows ce上运行一个应用程序?

c++ - 类型对齐会修改字体大小吗?

c++ - 为什么不能将类的类型成员作为模板参数传递?