Introduction to Programming Languages/Parametric Polymorphism

Parametric polymorphism
Parametric polymorphism occurs when a routine, type or class definition is parameterized by one or more types. It allows the actual parameter type to be selected by the user. This way, it is possible to define types or functions that are generics, which can be expressed by using type variables for the parameter type. The code below shows the use of a template, which is a way of implementing parametric polymorphism in C++.

The source code above defines a polymorphic function called  (lines 3 to 8). The type variable  defined in the scope of   is a kind of generics, which will be substituted at the function call. The function takes two parameters ( and  ) and returns a value of type. The runtime values of a and b are compared and the bigest is returned by the function. The main function shows two calls for the  function. At line 13 the function call uses the type  whereas at line 14 it uses the type. The content of the arguments in a GetMax function call is compared using the " " operator. For using this function, it is necessary that a variable type has this operator implemented. The following code shows an implementation of the overloading operator ">" in the class MyInt, so that it is possible to apply  on it. The main function shows its use.