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
struct C
{
void Foo(int) { }
};
void Bar(std::function 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)
.