C++11 lambda function

Bo Lorentsen bl at lue.dk
Sun Jul 23 08:36:22 CEST 2017


On 07/18/2017 10:28 AM, Bo Lorentsen wrote:
> Hi ...
>
> First, thanks for a really useful event library, it is a really good
> example in a minimalistic design.
>
> I have been using C++11 in production for a while, and I have been using
> lambda functions too, with all the benefit this gives in the code layout.
>
> So I like to know if anyone have tried to make use lambda functions as
> ev++ callbacks ?
>
> I found this article in on stacktrace :
> https://stackoverflow.com/questions/28746744/passing-lambda-as-function-pointer
>
> And it seems like it should be possible to make a capturing function
> pointer from an lambda, but I like to know if there is any other ideas
> as how to do this, or even plans to make this possible directly
> (ev++11.h :-)) ?
Ok, I answer this by this small extension to ev::io :

class zio : public ev::io {
    using fn_t = std::function<void(ev::io &watcher, int revents)>;
    fn_t _fn;
    void call( ev::io &watcher, int revents ) {
        _fn( watcher, revents );
    }
public:
    void set( fn_t fn ) {
        _fn = fn;
        io::set<zio, &zio::call>( this );
    }
};

This works really nice, and makes it possible to use C++ lambda calls,
and make the zio carry the context. There is a small overhead here, of
cause, but having this just inherit from ev::io, you only pay for what
you are using :-)

Hope someone may find this useful.

/BL
>
> Regards
>
> /BL
>
>





More information about the libev mailing list