我的之前的问题得出结论,使用C++ lambda函数(即函数对象)可能需要令人不悦的“双重转换”才能使用POSIX makecontext
。现在,我面临一个编译错误,与以下最小代码相关:
#include <iostream>
#include <ucontext.h>
using namespace std;
template <typename T> void foo() {
ucontext_t c;
auto f = [=](int i){ cout << i << endl; };
makecontext(&c, (void (*) (void)) (void (*)(int)) f, 1, 12345);
}
int main(int argc, char *argv[]) {
foo<int>();
return 0;
}
错误信息为:
error: invalid cast from type ‘foo() [with T = int]::<lambda(int)>’ to type ‘void (*)(int)’
然而,如果我从
foo
函数中删除未使用的(在此示例中)模板参数,使其变为void foo();
,并将调用更改为foo()
,则错误消失了。有人能告诉我为什么吗?我正在使用G++ 4.6。编辑:
从下面的评论中看来,代码中的
[=]
导致lambda成为一个“捕获”lambda,而实际上它并没有捕获任何东西。在我的代码中不需要[=]
,但遗憾的是,在GCC 4.6中用[]
替换并不能消除错误。我现在正在安装GCC 4.6.1...
c
添加到lambda体中,它将失败。 - Kerrek SBint
,j
,以便输出cout << i << " " << j << endl;
。 - user2023370