8.1 Introduction

Generics are templates for generating other types. These can be classes, objects, interfaces and even functions, arrays, records. It is a concept that comes from C++, where it is deeply integrated in the language. As of version 2.2, Free Pascal also officially has support for templates or Generics. They are implemented as a kind of macro which is stored in the unit files that the compiler generates, and which is replayed as soon as a generic class is specialized.

Creating and using generics is a 2-phase process.

  1. The definition of the generic is defined as a new type: this is a code template, a macro which can be replayed by the compiler at a later stage.
  2. A generic type is specialized: this defines a second type, which is a specific implementation of the generic type: the compiler replays the macro which was stored when the generic type was defined.

There are several units distributed with free pascal that implement generic containers and classes. For example the fgl unit.