Generic Programming

Read this text, which discusses the basics of generic programming and relates it to different languages.

3. Programming language support for genericity

3.1. In object-oriented languages

When creating container classes in statically typed languages, it is inconvenient to write specific implementations for each datatype contained, especially if the code for each datatype is virtually identical. For example, in C++, this duplication of code can be circumvented by defining a class template:

template <typename T>

class List {

  // Class contents.


List<Animal> list_of_animals;

List<Car> list_of_cars;

Above, T is a placeholder for whatever type is specified when the list is created. These "containers-of-type-T", commonly called templates, allow a class to be reused with different datatypes as long as certain contracts such as subtypes and signature are kept. This genericity mechanism should not be confused with inclusion polymorphism, which is the algorithmic usage of exchangeable sub-classes: for instance, a list of objects of type Moving_Object containing objects of type Animal and Car. Templates can also be used for type-independent functions as in the Swap example below:

// "&" passes parameters by reference

template <typename T>

void Swap(T& a, T& b) {

  T temp = b;

  b = a;

  a = temp;


std::string hello = "World!";

std::string world = "Hello, ";

Swap(world, hello);

std::cout << hello << world << std::endl;  // Output is "Hello, World!".

The C++ template construct used above is widely cited as the genericity construct that popularized the notion among programmers and language designers and supports many generic programming idioms. The D programming language also offers fully generic-capable templates based on the C++ precedent but with a simplified syntax. The Java programming language has provided genericity facilities syntactically based on C++'s since the introduction of J2SE 5.0.

C# 2.0, Oxygene 1.5 (also known as Chrome) and Visual Basic .NET 2005 have constructs that take advantage of the support for generics present in the Microsoft .NET Framework since version 2.0.