Skip to content

Generics and templates

Generics-GUI
Generics - GUI

When you face the matter of writing duplicated code, an idea generally rises about how to not waste time.

In strongly typed coding languages a simple mechanism exists, aiding the coder to solve the problem.
The so called Template.

They are designed so that classes and functions able to work with generic types, giving them the possibility to operate on different data types without the need of rewriting code for each of them.

Maybe you've just thought about the concept key: the abstraction.
Indeed we're dealing with it in the sense described above: a template is a try to avoid useless repeating code writing, and to do this we're forced to find a more general way than the direct and boring one.

Even if templates are not so easy to catch in mind on the first hit, the experience with them will illuminate you on the reason of their existence: yes, the main reason is clear, and obvious... but on the other hand a more complete picture is possible only when code takes form.

By resuming from our past projects and explanations, we've already used a type of generic items: TList.
Remember what it is?

TList is a container of generic pointers, which assume a specific nature when the TList's variable is declared: by being based on dynamic arrays, the pointed items must be of the same type: homogeneous data.
By assigning the specific nature, the compiler operates a casting.

With Templates and Generics (this last being the native templates mechanism's implementation in language) the casting operation acquires a more elastic aspect, so that the operation is called specialization.

Before this, let's see the pros and cons with templates.

Pros

  • Safety on types: they eliminate the explicit typecasting and the possible errors it can generate;
  • Maintainability: just one generic class code, specialized when required;
  • Code reuse: easy to create a set of reusable generic classes;
  • Efficiency and scalability: generic class types can be better adjusted for particular needs.

Cons

  • Little bit complex;
  • Bigger code: every specialized class is compiled separately, so producing additional code.

Now, let's see an example code, from the project you can download here.