O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.9. Mixing Generics and Templates

The C++ language includes support for mixing generic and template technologies in a way that attempts to acknowledge the relative value of both technologies. It achieves this by allowing class templates to implement generic interfaces. This means that you can create and expose a generic interface for your types while still leveraging all the power of templates for their implementation. To understand how significant and powerful this is, this section builds an example that exploits this very feature. You start by defining the following generic interface:

generic <typename T>
interface class IDataCollection {
    int GetNumItems();
    void AddItem(T newItem);
    T GetItem(int index);
    bool Validate();
};

This interface defines a basic data collection interface that can now be used in the declaration of a C++ class template. An example template that implements this interface might appear as follows:

template <class T>
ref class TemplateDataCollection : IDataCollection<T> {
private:
    List<T>^ _items;
public:
    TemplateDataCollection() {
        _items = gcnew List<T>();
    }

    virtual int GetNumItems() {
        return this->_items->Count;
    }

    virtual void AddItem(T newItem) {
        this->_items->Add(newItem);
    }

    virtual T GetItem(int index) {
        return this->_items[index];
    }

    virtual bool Validate() {
        bool retVal = true;
        for (int idx = 0; idx < _items->Count; idx++) {
            T item = _items[idx];
            if (item->IsValid() == false) {
                retVal = false;
                break;
            }
        }
        return true;
    }

};

As you can see, your class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required