Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate in C++11

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?

like image 507
dot222 Avatar asked Sep 01 '10 22:09

dot222


1 Answers

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).

like image 141
James McNellis Avatar answered Nov 15 '22 18:11

James McNellis