Why is bind () deprecated?

Reading a proposal for C ++ 17 about removing some obsolete, old and unused parts of the standard ( http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4190.htm ) i find section D .9 is a little weird:

D.9 "Binding" [des.lib.binders]

This defines bind1st () / bind2nd (), which have been strictly superseded by bind (). (In the future, I will argue that bind () itself has been superseded by lambdas and especially generic lambdas, so bind () should be deprecated, but that is not part of this proposal.)

What I am not getting is a comment about bind()

which is being replaced by lambdas.

If I have a class:

class A
{
  public:
    void f(int a){}
    void f(int a, int b){}
}

      

And I want to pass a pointer A::f

to some function someFunction

so that this function can call it on an object created from A

, I declare someFunction

:

void someFunction(const std::function<void(int, int)>&);

      

And call it:

A a;
someFunction(std::bind(static_cast<void (A::*)(int, int)> (&A::f),
                       std::ref(a), 
                       std::placeholders::_1,
                       std::placeholders::_2));

      

How can I achieve the same using a lambda? Can't it do anything that ca bind()

n't be done with a lambda?

+2


source to share


1 answer


How do you do it? Very direct and less esoteric (in my opinion) than the with std::ref

and placeholders_

.



#include <iostream>
#include <functional>

class A
{
public:
   void f(int a) {}
   void f(int a, int b) { std::cout << a + b << '\n';}
};

void someFunction(const std::function<void(int, int)>& f)
{
   f(1, 2);
}

int main()
{
   A a;
   someFunction([&] (int x, int y) { a.f(x, y); });
   return 0;
}

      

+7


source







All Articles