Generic Programming with Templates

Synopsis:

Templates support building parameterized types and functions that accept an unspecified type which gets resolved only when an application instantiates the code with a concrete type. Parameterized code will accept, without compilation error, arbitrary calls on instances of the template type. When an application instantiates the parameterized code with a concrete type compilation of the instantiated code succeeds if the type supports specified operations, else it fails.

So there are two C++ template compilation phases:

  1. Compilation of the template library code does a syntax check to identify known errors. No object code is generated since the type of the template parameter is not specified.
  2. Compilation of the instantiated application code generates an object file if instantiated syntax is correct, otherwise it fails.
This lazy syntax checking is very useful. C# and Java generics do eagar type checking so many operations that would succeed for useful types are not allowed because the compiler can't ensure that they will succeed.

Templates Presentation

Templates Code Examples:

References: