简体   繁体   English

非返回lambda,捕获为函数指针

[英]non returning lambda with captures as function pointer

My code (C++) need to pass lambda as function pointer. 我的代码(C ++)需要将lambda作为函数指针传递。 My lambdas always: a) return void; 我的lambdas总是:a)回归无效; b) never takes any parameter; b)从不采取任何参数; and c) can have zero or more capture arguments. 和c)可以有零个或多个捕获参数。 I want to pass this lambda as a function pointer but unable to do so. 我想将此lambda作为函数指针传递但无法执行此操作。 Any advice ? 有什么建议?

Sample code: 示例代码:

void fptrfunc(void (*fptr)()){ 
  fptr();
}

int main(){
  int x = 2;
  fptrfunc([](){cout << "LAMBDA CALL--1"<< endl; });            // Works
  fptrfunc([x](){cout << "LAMBDA CALL--2"<< endl; });           // Does not compile
  return 0;
} 

Lambda functions which are really just functions, ie, don't carry and data, can be converted to function pointers. Lambda函数实际上只是函数,即不携带和数据,可以转换为函数指针。 To not have any data clearly the capture has to be empty. 为了没有任何数据清楚,捕获必须是空的。 The other parts of the signature do't matter: as long as the types match, you can assign a lambda function [with an empty capture] to a function pointer. 签名的其他部分无关紧要:只要类型匹配,就可以将一个lambda函数[带有空捕获]赋值给函数指针。

The moment you need to have data with your lambda function you won't be able to convert it to a function pointer because there is no place to store the additional data. 当您需要使用lambda函数获取数据时,您将无法将其转换为函数指针,因为无法存储其他数据。 If you have a sensible interface where you need to pass the lambda function you may have some user data being passed along, often a void* . 如果你有一个合理的接口,你需要传递lambda函数,你可能会传递一些用户数据,通常是void* You could a combination of an auxiliary function pointer and a lambda, probably wrapped by a suitable std::function<Sig> , pointed to by the user data to still call a lambda function. 你可以使用一个辅助函数指针和一个lambda的组合,可能由一个合适的std::function<Sig>包裹,用户数据指向它仍然可以调用lambda函数。

What you want, is not possible in C++. 你想要什么,在C ++中是不可能的。 Lambdas that capture variables are not convertible to a function pointer. 捕获变量的Lambda不能转换为函数指针。

You need to do drop the requirement c) and only use lambdas without captures. 你需要放弃要求c)并且只使用没有捕获的lambdas。 Or you must change the declaration of fptrfunc . 或者您必须更改fptrfunc的声明。 You can change the parameter type to std::function or make it a template that can accept any type of functor that implements the operator() . 您可以将参数类型更改为std::function或使其成为可以接受任何类型的实现operator()的仿函数的模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM