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 Generic_Stack is procedure Push(E : in Item); procedure Pop (E : out Item); Overflow, Underflow : exception; end Generic_Stack;
Now a definition needs to be implemented, so here's a sample implementation:
package body Generic_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 Generic_Stack;
Somewhere else you can instantiate the 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 Generic_Stack(Size => 200, Item => Integer);
The ``Size =>'' and ``Item =>'' are optional; you could omit them if you wanted to, but including them makes the code clearer. From then on, you could "Push" a new Integer onto Stack_Int by saying:
What are the formal parameters for generic package Stack?
|Go back to the previous section||Skip to the next section||Go up to lesson 11 outline|
David A. Wheeler (firstname.lastname@example.org)
The master copy of this file is at
The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s11s3.htm".