c++11lambdalibeventboost-lambda

Can I use C++11 lambda with libevent?


There is a callback function type in libevent used by event_new().

typedef void (*event_callback_fn)(evutil_socket_t, short, void *);

I want use lambda with event_callback_fn.

If I use

[](evutil_socket_t fd, short flags, void * _param){}

everything is OK.
But if I use the lambda capture list

[&](evutil_socket_t fd, short flags, void * _param){} 

event_new() will not be compiled.


Solution

  • The type alias

    void (*event_callback_fn)(evutil_socket_t, short, void *);
    

    is a function pointer. Lambdas can automatically convert to function pointers, when they don't capture anything. As soon as you define a closure (stateful lambda), you can't pass it as an argument of type event_callback_fn.