问题
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?
回答1:
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;
}
来源:https://stackoverflow.com/questions/33835922/why-should-bind-be-deprecated