Does C++11 provide delegates?
If not, what is the best (most efficient) way to do something similar in C++? Boost.Signals? FastDelegate? Something else?
You can get delegate-like semantics using bind
to bind a member function to a class instance:
#include <functional>
struct C
{
void Foo(int) { }
};
void Bar(std::function<void(int)> func)
{
func(42); // calls obj.Foo(42)
}
int main()
{
using namespace std::placeholders;
C obj;
Bar(std::bind(&C::Foo, obj, _1));
}
In this example, Bar()
takes anything that has a single int
parameter and that returns void
.
In main()
, we bind a pointer to the member function C::Foo
to the instance of C
named obj
. This gives us an object that can be called with a single int
parameter and which returns void
.
We call Bar()
with this object and Bar()
makes the call obj.Foo(42)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With