tags:

views:

170

answers:

3

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;
}
+12  A: 

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 possible.

Terry Mahaffey
Do you remember what section that was in? This is interesting.
rlbond
@rlbond: N3090/3092, §5.1.2/6
Jerry Coffin
A: 

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.

Noah Roberts
+3  A: 

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);
}
FredOverflow