13.2 Generic functions
Like generic procedure, we can build generic functions, and the same guidelines are applicable except, in addition it is desirable to provide user with generic functions for default types. Here is an example of a generic function.
generic -- function squaring
type Element is private;
with function "<" ( Left, Right : Element_type ) return Boolean is <>;
with function Equal ( Left, Right : Element_type ) return Boolean is "=";
with function "*" ( Left, Right : Element ) return Element;
function Squaring ( X : Element ) return Element;
function Squaring ( X : Element ) return Element is
begin
return X * X;
end Squaring;
After compiling successfully, it can be instantiated for different situations.
function Square is new Squaring(Integer, "*");
Guideline1 : Define generic functions for overloading of operators used.
Guideline2 : Use box as a default type for generic formal function for overloading operator.
with function "<" ( Left, Right : Element_type ) return Boolean is <>;
Guideline3 : Generic functions can be instantiated by providing actual
parameters as shown below.
function Square is new Squaring(Integer, "*");
It can be called like usual function calls.
A := Square ( A );