6

Reading the proposal for C++17 about removing some deprecated, 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 a bit strange:

D.9 "Binders" [depr.lib.binders]

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

What I don't get is the comment about bind() itself being superseded 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 function pointer to A::f to some function, someFunction, so that this function can call it on an object instantiated 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 do I achieve the same thing using a lambda? Is there really nothing that bind() can do, which cannot be done with a lambda?

4
  • 1
    C++14 has generic lambdas ( auto f = [](auto x) { ... }). Still I like bind and I don't think that it should be ever deprecated. Commented Nov 20, 2015 at 21:00
  • 2
    The section in this paper Appendix: Why we need bind when we have a generic lambda? makes the case for bind still be useful but it does not seem like a strong case. Commented Nov 20, 2015 at 21:01
  • 1
    @ShafikYaghmour The example in the summary there makes a pretty strong case for me :) Commented Nov 20, 2015 at 21:07
  • It is definitely a matter of perspective :-) I guess what I mean is there is no argument of a something that bind can do that a lambda can not. We can of course disagree on usability. Commented Nov 20, 2015 at 21:08

1 Answer 1

10

How do you do it? Very straight forward and less esoteric (my opinion) than the bind example 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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.