3.2. Run-Time vs. Compile-Time

Generics and C++ templates take very different approaches to how and when objects are instantiated. Generics are instantiated at run-time by the CLR, and templates are instantiated at compile-time. This fundamental difference is at the root of almost every point of variation between generics and templates. And, as you will see, these variations end up creating a fairly significant ideological divide between these two technologies.

In the sections that follow you'll be exposed to the specific implications of run-time and compile-time instantiation. Understanding the mechanics of these two varying approaches will provide a good foundation for the rest of this discussion.

3.2.1. Compile-Time Instantiation (Templates)

The term "templates" does an excellent job of conveying how a compiler processes templates. When you declare a template in C++, the code you write is providing a series of type placeholders that will be replaced with actual types at compile time. Let's look at a simple declaration of a C++ template class to see how the compiler will process it:

template <class T>
class Stack {
    public:
       Stack(int = 10) ;
       ~Stack() { delete [] stackPtr; }
       int push(const T&);
       int pop(T&);
       int isEmpty() const { return top == −1; }
       int isFull() const { return top == size - 1; }
    private:
       int size;
       int top;
       T* stackPtr;
};

This class defines a Stack template that can be used to perform all the basic operations to maintain the state of a stack container. As a template, ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.