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?
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?
The C mechanism has always been function pointer & baton (except for qsort() and bsearch() which didn't take a baton).
So one would always pass the class object as the baton.
E.G.:
You don't necessarily need to wait for C++0x. You can implement Delegates almost as well in the current C++03 standard. You simply have to overload the operator (), so as you can call
MyObjectFunctor functor; functor();
and since the functor is an object, you can pass it as a delegate/object into functions;the current version of the STL defines the header
<algorithm>
that provides functions ready to be used with Functors/Lambdas/Delegates.simple example of a functor.
You don't need c++0x. in
<functional>
you havebind1st
bind2nd
mem_fun
andmem_fun_ref
. You also have Boost.Bind which generalizes all of the above functions (IIRC).Going from memory ...
Though
std::function
works nicely, I would like to point out this nice piece of delegate code, written here (including example usage!). Following the references and answers there you can read all about how thisDelegate
class is constructed and why it may be faster thanstd::function
.Note also my question here for a problem I encountered with it on VS 2015.
You can get delegate-like semantics using
bind
to bind a member function to a class instance:In this example,
Bar()
takes anything that has a singleint
parameter and that returnsvoid
.In
main()
, we bind a pointer to the member functionC::Foo
to the instance ofC
namedobj
. This gives us an object that can be called with a singleint
parameter and which returnsvoid
.We call
Bar()
with this object andBar()
makes the callobj.Foo(42)
.