12.8. Generic Delegates in C++

Generic delegates, like interfaces, are a very simple generic construct. A generic delegate uses type parameters to create a single delegate signature that can be used as the delegate type for a myriad of delegate implementations. This eliminates the need to create separate delegate declarations to support each of the possible delegate signatures you may need to support in your application. So, although there's not a lot of complexity to generic delegates, they are extremely useful. Here's a small delegate sample that shows how generic delegates are represented in C++:

generic <typename T>
delegate void MyDelegate(T param);

void UpdateStatus(DataObject^ dataObj) {
    if (dataObj->GetStatus() <= 2) {
        Console::WriteLine("Status updated");
        dataObj->SetStatus(999);
    }
}

void UpdateSalary(DataObject^ dataObj) {
    double salary = dataObj->GetSalary();
    Console::WriteLine("Salary Before : {0}", salary);
    salary *= 1.2;
    Console::WriteLine("Salary After  : {0}", salary);
    dataObj->SetSalary(salary);
}

generic <typename T>
ref class DataObjects : List<T> {
private:
    MyDelegate<T>^ _delegate;
public:
    DataObjects(MyDelegate<T>^ aDelegate) : _delegate(aDelegate) {
    }

    void SetUdpater(MyDelegate<T>^ newDelegate) {
        this->_delegate = newDelegate;
    }

    void UpdateItems() {
        for (int idx = 0; idx < Count; idx++) {
            T dataObj = this[idx];
            _delegate->Invoke(dataObj);
        }
    }
};

This example has three basic elements. First, and most significant here, is the declaration of the delegate MyDelegate<T> ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.