3.3. Templates Extras

A handful of features that are part of templates are not part of generics. The following sections provide a brief overview of each of these areas. If you are part of the generics-only crowd, this will help you understand what additional features are available to you in the world of templates. If you are template-aware, this section will further qualify those features that are not currently supported by generics.

3.3.1. Template Specialization

With templates, developers are allowed to create specializations of a template that provide alternative implementations based on a type argument. Consider the following example of a Stream template class that includes a specialization for the long type argument:

template <class T>
class stream {
    public:
        void foo() { cout << "Called stream<T>::foo()" << endl; }
};

template <>
class stream<long> {
    public:
        void foo() { cout << "Called stream<long>::foo()" << endl; }
};

int main() {
 stream<char> charStream;
 stream<long> longStream;
 return 0;
}

You'll notice in this example that two stream templates are declared, each with its own implementation of the foo() method. The first of these two templates will be used for the majority of type arguments. The second template will only be invoked if you supply a long type argument. The idea here is that you can provide specializations for any number of data types. Generics have no equivalent to this concept.

3.3.2. Non-Type Parameters

Templates support the ability to accept what ...

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.