Parametric polymorphism
The idea of code reuse arises from the necessity for constructing large software systems combining well-established building blocks. The reusability of code improves the productivity and the quality of software. The generic units are one of the ways in which the Ada language supports this characteristic. A generic unit is a subprogram or package that defines algorithms in terms of types and operations that are not defined until the user instantiates them.
Note to C++ programmers: generic units are similar to C++ templates.
For example, to define a procedure for swapping variables of any (non-limited) type:
generic
type Element_T is private; -- Generic formal type parameter
procedure Swap (X, Y : in out Element_T);
procedure Swap (X, Y : in out Element_T) is
Temporary : constant Element_T := X;
begin
X := Y;
Y := Temporary;
end Swap;
The Swap
subprogram is said to be generic. The subprogram specification is preceded by the generic formal part consisting of the reserved word generic followed by a list of generic formal parameters which may be empty. The entities declared as generic are not directly usable, it is necessary to instantiate them.
To be able to use Swap
, it is necessary to create an instance for the wanted type. For example:
procedure Swap_Integers is new Swap (Integer);
Now the Swap_Integers
procedure can be used for variables of type Integer
.
The generic procedure can be instantiated for all the needed types. It can be instantiated with different names or, if the same identifier is used in the instantiation, each declaration overloads the procedure:
procedure Instance_Swap is new Swap (Float);
procedure Instance_Swap is new Swap (Day_T);
procedure Instance_Swap is new Swap (Element_T => Stack_T);
Similarly, generic packages can be used, for example, to implement a stack of any kind of elements:
generic
Max: Positive;
type Element_T is private;
package Generic_Stack is
procedure Push (E: Element_T);
function Pop return Element_T;
end Generic_Stack;
package body Generic_Stack is
Stack: array (1 .. Max) of Element_T;
Top : Integer range 0 .. Max := 0; -- initialise to empty
-- ...
end Generic_Stack;
A stack of a given size and type could be defined in this way.
Source: Ada Programming