gpt4 book ai didi

c++ - 将带有捕获的 lambda 传递给遗留回调

转载 作者:可可西里 更新时间:2023-11-01 18:18:31 24 4
gpt4 key购买 nike

我在 C++11 项目中使用 C 库,这个 C 库提供了一个需要函数指针的函数。我想将一个 C++11 lambda 传递给它,它可以正常工作,除非我捕获变量。这是一个简短的例子:

#include <cstdio>
#include <functional>

typedef int (*Callback)();

void legacy(Callback callback) {
printf("%i\n", callback());
}

int stdCallback() {
return 1;
}

int main(int argc, char* argv[]) {
int number = 3;

// Standard C callback works
legacy(stdCallback);

// Lambda without capturing works
legacy([]() { return 2; });

// Lambda with capturing doesn't work
legacy([&]() { return number; });

return 0;
}

GNU C++ 编译器在第三次调用 legacy 函数时给出以下错误消息:

test.cpp: In function ‘int main(int, char**)’:
test.cpp:24:36: error: cannot convert ‘main(int, char**)::<lambda()>’ to ‘Callback {aka int (*)()}’ for argument ‘1’ to ‘void legacy(Callback)’
legacy([&]() { return number; });

我该如何解决这个问题?或者在技术上不可能将捕获的 lambda 用作 C 函数指针?

最佳答案

不,如果 lambda 捕获任何内容,则不能将其转换为函数指针。

C++ 标准,第 5.1.2/6 节:[expr.prim.lambda],强调我的:

The closure type for a non-generic lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function with C ++ language linkage (7.5) having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator

关于c++ - 将带有捕获的 lambda 传递给遗留回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com