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

Scott Meyers gave a talk about this. This is what I remember:

In C++14 there is nothing useful bind can do that can’t also be done with lambdas.

In C++11 however there are some things that can’t be done with lambdas:

  1. You can’t move the variables while capturing when creating the lambdas. Variables are always captured as lvalues. For bind you can write:

    auto f1 = std::bind(f, 42, _1, std::move(v));
    
  2. Expressions can’t be captured, only identifiers can. For bind you can write:

    auto f1 = std::bind(f, 42, _1, a + b);
    
  3. Overloading arguments for function objects. This was already mentioned in the question.

  4. Impossible to perfect-forward arguments

In C++14 all of these possible.

  1. Move example:

    auto f1 = [v = std::move(v)](auto arg) { f(42, arg, std::move(v)); };
    
  2. Expression example:

    auto f1 = [sum = a + b](auto arg) { f(42, arg, sum); };
    
  3. See question

  4. Perfect forwarding: You can write

    auto f1 = [=](auto&& arg) { f(42, std::forward<decltype(arg)>(arg)); };
    

Some disadvantages of bind:

  • Bind binds by name and as a result if you have multiple functions with the same name (overloaded functions) bind doesn’t know which one to use. The following example won’t compile, while lambdas wouldn’t have a problem with it:

    void f(int); void f(char); auto f1 = std::bind(f, _1, 42);
    
  • When using bind functions are less likely to be inlined

On the other hand lambdas might theoretically generate more template code than bind. Since for each lambda you get a unique type. For bind it is only when you have different argument types and a different function (I guess that in practice however it doesn’t happen very often that you bind several time with the same arguments and function).

What Jonathan Wakely mentioned in his answer is actually one more reason not to use bind. I can’t see why you would want to silently ignore arguments.

Leave a Comment