Can a lambda expression be passed as function pointer?

我是研究僧i 提交于 2019-12-04 09:08:09

问题


I am trying to pass a lambda expression to a function that takes a function pointer, is this even possible?

Here is some sample code, I'm using VS2010:

#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); //DOES NOT COMPILE
    return 0;
}

回答1:


In VC10 RTM, no - but after the lambda feature in VC10 was finalized, the standard committee did add language which allows stateless lambdas to degrade to function pointers. So in the future this will be possible.




回答2:


You can use std::function for this:

void fptrfunc(std::function<void (int)> fun, int j)
{
    fun(j);
}

Or go completely generic:

template <typename Fun>
void fptrfunc(Fun fun, int j)
{
    fun(j);
}



回答3:


This works in VS2010:

template<class FunctorT>
void* getcodeptr(const FunctorT& f) {
  auto ptr = &FunctorT::operator();
  return *(void**)&ptr;
} 

void main() {
  auto hello = [](char* name){ printf("hello %s\n", name); };
  void(*pfn)(char*) = (void(*)(char*)) getcodeptr(hello);
  pfn("world");
}



回答4:


No. It cannot. Not dependably at least. I know that VS2010 implements them as object functors. Based on how they work that may be an a priori requirement.




回答5:


As long as the lambda doesn't use capture clause (i.e. doesn't capture variables from above it), it can be used as a function pointer. VC compiler internally generates anonymous functions with different calling convention so that it can be used without issues.



来源:https://stackoverflow.com/questions/2993330/can-a-lambda-expression-be-passed-as-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!