Saturday, December 27, 2008

C# Delegates in Standard C++ Part 1

In C#, delegates are a very simple and a well designed implementation of functors (in my opinion, of course!). It is built into the C# language and does not take very many lines of code to instantiate a delegate object. Below, I will demonstrate how this can be implemented in standard C++ code.

The idea for a delegate or a functor is that a piece of code (like a button click handler) will need to notify one or many other pieces of code that handle the event. It's also important that the code that is firing the event and the code that is handling the event have a loose coupling between each other. This is very important in large software systems that need to be often reworked. This guarantees that a developer does not have to rewrite code in areas of the system that shouldn't be changed.

Here is some code to demonstrate:


// Object that is able to be accessed by the events and handlers
NullaryDelagate someDelegate;
.
.
.
.
class MyHandlerMethods
{
public:

MyHandlerMethods()
{
// Add some the methods to the delegate...
someDelegate += DelagateFactory::Create(this, &MyHandlerMethods::Method1);
someDelegate += DelagateFactory::Create(this, &MyHandlerMethods::Method2);
someDelegate += DelagateFactory::Create(this, &MyHandlerMethods::Method3);

}

void Method1()
{
PrintToConsole("Method 1");
}

void Method2()
{
PrintToConsole("Method 2");
}

void Method3()
{
PrintToConsole("Method 3");
}
} HandlerObj; // For this demonstration, this object is made global.
.
.
.
void main()
{
// Invokes all of the handler messages.
someDelegate();
}

This is very similar to the observer pattern, except the handlers are invoked by overloading the call function operator overload.

Next time I will go over the specifics on how to use my library to get delegates running in your code.