What is the general idea of a delegate in C++? What are they, how are they used and what are they used for?
I'd like to first learn about them in a 'black box' way, but a bit of information on the guts of these things would be great too.
This is not C++ at its purest or cleanest, but I notice that the codebase where I work has them in abundance. I'm hoping to understand them enough, so I can just use them and not have to delve into the horrible nested template awfulness.
These two The Code Project articles explain what I mean but not particularly succinctly:
Best Answer
You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.
Option 1 : functors:
A function object may be created by implementing
operator()
Option 2: lambda expressions (C++11 only)
Option 3: function pointers
Option 4: pointer to member functions (fastest solution)
See Fast C++ Delegate (on The Code Project).
Option 5: std::function
(or
boost::function
if your standard library doesn't support it). It is slower, but it is the most flexible.Option 6: binding (using std::bind)
Allows setting some parameters in advance, convenient to call a member function for instance.
Option 7: templates
Accept anything as long as it matches the argument list.