This is basically a question about the readability, style, performance of 2 different approaches to creating/passing a functor that points to a member method from within a class constructor/method.
Approach 1:
using namespace std::placeholders;
std::bind( &MyClass::some_method, this, _1, _2, _3 )
Approach 2:
[ this ](const arg1& a, arg2 b, arg3& c) -> blah { some_method( a, b, c ); }
I was wondering if using the lambda is just gratuitous in this situation, in some respects it is easier to see what is going on, but then you have to explicitly provide the arg types. Also i prefer not to have "using namespace whatever;" but then it makes the bind expression needlessly verbose (eg. _1 becomes std::placeholders::_1), and lambda avoids this issue.
Finally i should note that for the purposes of this question, some_method is a big function that does lots of things, and would be a pain to directly copy into a lambda body.
If this question seems too vague, then we can focus on answers to the performance differences, if any.
EDIT: A non-trivial use case.
MyClass::MyClass()
: some_member_( CALLBACK_FUNCTOR )
{}
As you can see, the CALLBACK_FUNCTOR used in an initializer list (defined with approach 1 or 2) makes it difficult to scope a using declaration (afaik), and obviously we wouldnt bother wrapping a member method that we intended to call straight away.
As far as readability and style are concerned, I think std::bind looks cleaner for this purpose, actually. std::placeholders does not have anything other than _[1-29] for use with std::bind as far as I know, so I think it is fine to just use "using namespace std::placeholders;"
As for performance, I tried disassembling some test functions:
When foo() was not defined in the same translation unit, the assembly outputs were more or less the same for both test_lambda and test_bind:
However, when the body of foo was included into the same translation unit, only the lambda had its contents inlined (by GCC 4.6):
Out of curiosity, I redid the test using GCC 4.7, and found that with 4.7, both tests were inlined in the same manner.
My conclusion is that the performance should be the same in either case, but you might want to check your compiler output if it matters.
It seems that this is your problem with using
std::bind
. You can use below simple trick to overcome it.Demo.
Some updated advise i found useful: IStephan T. Lavavej advise on not binding "Avoid using bind(), use lambdas". https://www.youtube.com/watch?v=zt7ThwVfap0&t=32m20s is pretty good.
example for a wrapping of a member function in a lambda function and sending to a 2nd matrix object's member function to apply with that function.
so to recap: