Hacker News new | comments | show | ask | jobs | submit login

> It's also unfortunate to note that, at least in g++ and clang, there is still significant advantage to using lambdas over std::function and std::bind.

I have to say, std::bind is just a travesty. It's so difficult to bind a member function pointer that takes multiple arguments to an std::function.

I wrote my own so that you can do this with just: function<void (int, int)> f = {&Class::func, &object};

Source is here: http://hastebin.com/raw/kobudabasa

In doing so, it becomes clear there's basically two ways to implement this idea:

1. you allocate heap space to perform type erasure. This results in a pointer indirection plus a virtual function call worth of added overhead. Along with tremendous costs to allocate and destroy the function objects.

2. you store a big chunk of raw memory inside the function<> class, and cast it as necessary to a pointer. This is actually what I did prior to C++11 and lambdas. It was tricky because the size of member function pointers is undefined. Having a vtable makes them larger. So for that I made a complex dummy class to pull its sizeof info.

Option 2 is definitely a good bit faster (at least for constructing/copying/reassigning/destructing them), but you're really butting up against undefined behavior and abusing the language. And capturing lambdas would be even more challenging.

But even with that, yeah, you can't ever really beat concepts that are native to the language like lambdas and virtual functions themselves. Compilers can get really clever and inline things in a way that's exceedingly unlikely to ever occur with std::function, no matter how you implement it.

I've also written my own "version" of function but intentionally lightweight, for an embedded project: https://github.com/ambrop72/aprinter/blob/master/aprinter/ba...

Callback<void(int, int)> f = APRINTER_CB_OBJFUNC(&ThisClass::function, this);

One magic thing is that the macro is just a value, it figures out the type itself.

There's zero memory allocation. The Callback class just contains a function pointer and a void pointer. So you can't bind argument values other than the object pointer, but I have no need for that.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact