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 ...
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.