Equivalent to C # delegate when using C ++ with smart pointers

I am basically a .NET programmer working on a C ++ project and am trying to define an equivalent way to handle delegates using the Action and Function template types. I use delegates for both events and callbacks in .NET code. My C ++ project uses smart pointers and the same delegate design patterns as the C # program. What is the best way to handle this situation? It is not clear to me how to pass and maintain a pointer to a function that also tracks the smart pointer and potentially removes the underlying object, as the event container uses a weak reference. The library must be multi-platform, so using the CLR is unfortunately not an option.

+4
source share
2 answers

What you are looking for is a method pointer associated with an existing object, what is it?

You should look for boost :: bind . If your environment supports it, you can also use std::tr1::bind or even std::bind if it supports C ++ 11.

An example illustrating what you want:

 struct X { bool f(int a); }; X x; shared_ptr<X> p(new X); int i = 5; bind(&X::f, ref(x), _1)(i); // xf(i) bind(&X::f, &x, _1)(i); //(&x)->f(i) bind(&X::f, x, _1)(i); // (internal copy of x).f(i) bind(&X::f, p, _1)(i); // (internal copy of p)->f(i) 

The last two examples are interesting in that they create "autonomous" functional objects. bind (& X :: f, x, _1) stores a copy of x. bind (& X :: f, p, _1) stores a copy of p, and since p is boost :: shared_ptr, the function object maintains a reference to its X instance and remains valid even when p exits or reset ().

For the differences between boost::bind , std::tr1::bind and std::bind , I let you see this other SO question.

+1
source

Take a look at: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

This will also explain why C ++ delegates are a bit complicated. This library was recommended in the game development book I read (so I accept it very quickly).

0
source

All Articles