Section 11.3 - Example of a Generic Package

Let's look an example of a generic package. This example of a generic package is straight from the Ada 95 RM section 12.8.

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:

  Stack_Int.Push(7);


Quiz:

What are the formal parameters for generic package Stack?

  1. Size, Positive, Item, and private.
  2. Size and Item.
  3. Size.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 11 outline

David A. Wheeler (dwheeler@dwheeler.com)

The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s11s3.htm".