Ralph Tandetzky Ralph Tandetzky - 23 days ago 9
C++ Question

Why use std::bind over lambdas in C++14?

Before C++11 I used

boost::bind
or
boost::lambda
a lot. The
bind
part made it into the standard library (
std::bind
) the other part became part of the core language (C++ lambdas) and made the use of lambdas a lot easier. Nowadays, I hardly use
std::bind
, since I can do almost anything with C++ lambdas. There's one valid use-case for
std::bind
that I can think of:

struct foo
{
typedef void result_type;

template < typename A, typename B >
void operator()(A a, B b)
{
cout << a << ' ' << b;
}
};

auto f = bind(foo(), _1, _2);
f( "test", 1.2f ); // will print "test 1.2"


The C++14 equivalent for that would be

auto f = []( auto a, auto b ){ cout << a << ' ' << b; }
f( "test", 1.2f ); // will print "test 1.2"


Much shorter and more concise. (In C++11 this does not work yet because of the auto parameters.) Is there any other valid use case for
std::bind
beating the C++ lambdas alternative or is
std::bind
superfluous with C++14?

Answer

std::bind can still do one thing polymorphic lambdas can't: invoke overloaded functions

struct F {
  bool operator()(char, int);
  std::string operator()(char, char);
};

auto f = std::bind(F(), 'a', std::placeholders::_1);
bool b = f(1);
std::string s = f('b');

The call wrapper created by the bind expression calls different functions depending on the arguments you give it, the closure from a C++14 polymorphic lambda can take different types of arguments but can't take a different number of arguments, and always invokes (specializations of) the same function on the closure. Correction: see the comments below

The wrapper returned by std::bind can also be called with too many arguments and it will ignore them, whereas a closure created by a lambda will diagnose attempts to pass too many arguments ... but I don't consider that a benefit of std::bind :)