Every time I need to use std::bind
, I end up using a lambda instead. So when should I use std::bind
? I just finished removing it from one codebase, and I found that lambdas were always simpler and clearer than std::bind
. Isn't std::bind
completely unnecessary? Shouldn't it be deprecated in the future? When should I prefer std::bind
to lambda functions? (There has to be a reason that it got into the standard at the same time as lambdas.)
I've also noticed that more and more people are familiar with lambdas (so they know what lambdas do). However, a lot fewer people are familiar with std::bind
and std::placeholders
.
You can create polymorphic objects with
std::bind
which you can't with lambdas, i.e. the call wrapper returned bystd::bind
can be invoked with different argument types:I created this as a puzzle not an example of good code, but it does demonstrate polymorphic call wrappers.
Here's something you can't do with a lambda:
Lambdas can't capture move-only types; they can only capture values by copy or by lvalue reference. Though admittedly this is a temporary issue that's being actively resolved for C++14 ;)
"Simpler and clearer" is a matter of opinion. For simple binding cases,
bind
can take a lot less typing.bind
also is focused solely on function binding, so if you seestd::bind
, you know what you're looking at. Whereas if you use a lambda, you have to look at the lambda implementation to be certain of what it does.Lastly, C++ does not deprecate things just because some other feature can do what it does.
auto_ptr
was deprecated because it is inherently dangerous to use, and there is a non-dangerous alternative.