Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a lambda expression be passed as function pointer?

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; } 
like image 904
LoudNPossiblyWrong Avatar asked Jun 07 '10 21:06

LoudNPossiblyWrong


People also ask

Is lambda function a function pointer?

A lambda expression with an empty capture clause is convertible to a function pointer. It can replace a stand-alone or static member function as a callback function pointer argument to C API.

Which can be passed in function pointers?

which of the following can be passed in function pointers? Explanation: Only functions are passed in function pointers.

Can you use a pointer on an function?

You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.


2 Answers

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.

like image 198
Terry Mahaffey Avatar answered Sep 20 '22 13:09

Terry Mahaffey


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); } 
like image 40
fredoverflow Avatar answered Sep 21 '22 13:09

fredoverflow