Summary
In this chapter we describe the generic mechanism which allows a special form of parameterization at compile time which can be applied to subprograms and packages. The generic parameters can be types of various categories (access types, limited types, tagged types and so on), subprograms and packages as well as values and objects.
Genericity is important for reuse. It provides static polymorphism as opposed to the dynamic polymorphism provided by type extension and class wide types. Being static it is intrinsically more reliable but usually less flexible. However, in the case of subprogram parameters it does not have the convention restrictions imposed by access to subprogram types and thus is particularly useful where the parameter is an operation.
Package parameters enable the composition of generic packages while ensuring that their instantiations are compatible. They can also be used to group together the parameters of other generic units to provide signatures.
Declarations and instantiations
We often get the situation that the logic of a piece of program is independent of the types involved and it therefore seems unnecessary to repeat it for all the different types to which we might wish it to apply. A simple example is provided by the procedure Swap of Exercise 10.3(1)
procedure Swap(X, Y: in out Float) is
T: Float;
begin
T := X; X := Y; Y := T;
end;
It is clear that the logic is independent of the type Float. If we also wanted to swap integers or dates we could write other similar procedures but this would be tedious. The generic mechanism allows us to avoid this. We declare
generic
type Item is private;
procedure Exchange(X, Y: in out Item);
procedure Exchange(X, Y: in out Item) is
T: Item;
begin
T := X; X := Y; Y := T;
end;
The subprogram Exchange is a generic subprogram and acts as a kind of template. The subprogram specification is preceded by the generic formal part consisting of the reserved word generic followed by a (possibly empty) list of generic formal parameters. The subprogram body is written exactly as normal but note that, in the case of a generic subprogram, we always have to give both the specification and the body separately.
A generic procedure is not a real procedure and so cannot be called; but from a generic procedure we can create an actual procedure by a mechanism known as generic instantiation.
- Type
- Chapter
- Information
- Programming in Ada 2012 , pp. 469 - 500Publisher: Cambridge University PressPrint publication year: 2014