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

标签 c++ c++11 lambda

我在 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/

相关文章:

java - 结合对象的 ArrayList 并在 Java 中对 BigDecimal 求和

c++ - 使用新对象重新分配 `unique_ptr` 值的便捷类型推断方法

c++ - 在现代 C++ 中实现专门的数据结构

c++ - 通过来自任意索引的参数包初始化 std::array

javascript - 使用 CoffeeScript 从对象数组中选择一个字段

python - Pandas - 将列值组合到新列中的列表中

c++ - 防止用户创建类的未命名实例

c++ - 如何在 C++ 中遍历数字列表

C++ 为什么箭头 (->) 运算符的自动重新应用不适用于指针到指针类型?

c++ - 为什么不能在新的初始化程序中省略数组大小?