Let's imagine that you want to create a generic package for a Stack that takes operations Push and Pop. Here's one way to define such a Stack; we'll define a Stack package that stores some Item type and has a maximum size:
generic Size : Positive; type Item is private; package Stack is procedure Push(E : in Item); procedure Pop (E : out Item); Overflow, Underflow : exception; end Stack;
Now a definition needs to be implemented, so here's a sample implementation:
package body Stack is type Table is array (Positive range <>) of Item; Space : Table(1 .. Size); Index : Natural := 0; procedure Push(E : in Item) is begin if Index >= Size then raise Overflow; end if; Index := Index + 1; Space(Index) := E; end Push; procedure Pop(E : out Item) is begin if Index = 0 then raise Underflow; end if; E := Space(Index); Index := Index - 1; end Pop; end Stack;
Somewhere else you can instantiate this generic Stack package. If you wanted to instantiate a new package called ``Stack_Int'' which could hold 200 Integers, you could say:
package Stack_Int is new Stack(Size => 200, Item => Integer);
The ``Size =>'' and ``Item =>'' are optional; you could omit them if you wanted to. From then on, you could "Push" a new Integer onto Stack_Int by saying:
Stack_Int.Push(7);
Go back to the previous section
Go up to the outline of lesson 11
David A. Wheeler (wheeler@ida.org)