Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Strong Typing and Generics

Generics in Ada: Reusable Packages and Subprograms

Write reusable Ada code with generic subprograms and packages, formal type, object and subprogram parameters, instantiation, the standard containers and the difference from C++ templates.

A generic unit is a template for a package or subprogram, parameterized by types, values or subprograms. You write the algorithm once, then instantiate it for the types you need. Ada's standard library is full of generics: containers, numeric I/O (Integer_IO) and sorting are all instantiated from generic units.

Unlike C++ templates, an Ada generic is checked once, against the contract of its formal parameters, so a mistake is reported at the definition and not deep inside an instantiation. Ada code is read-only on this site; C stand-ins model the same idea.

A generic subprogram

ADA
generic
   type Item is private;
procedure Swap (A, B : in out Item);

procedure Swap (A, B : in out Item) is
   Temp : constant Item := A;
begin
   A := B;
   B := Temp;
end Swap;

The generic formal part (everything between generic and the unit) declares what the unit needs. type Item is private; means "any type that can be copied and compared for equality". To use it, instantiate:

ADA
procedure Swap_Int is new Swap (Item => Integer);
procedure Swap_Str is new Swap (Item => Unbounded_String);

X, Y : Integer := 1;
...
Swap_Int (X, Y);

An instantiation is an ordinary subprogram. It is fully type-checked, and the compiler may share the code between instances.

Formal type kinds

The syntax of the formal type states the operations the generic body may rely on:

Formal What the actual type must provide
type T is private; any definite type with assignment
type T is limited private; any type, even limited
type T is (<>); a discrete type (integer or enumeration)
type T is range <>; a signed integer type
type T is digits <>; a floating-point type
type T is array (Index) of Element; an array type
type T is tagged private; a tagged type (for OOP)

Because the generic body only uses what its formal declares, it cannot accidentally call + on Item when the formal says only private. To use an operation, you ask for it explicitly as a formal subprogram.

Formal subprograms and values

ADA
generic
   type Element is private;
   type Index   is range <>;
   type Vector  is array (Index range <>) of Element;
   with function "<" (L, R : Element) return Boolean is <>;
procedure Sort (V : in out Vector);

with function "<" ... is <> says "the actual type must supply a <; by default use the one visible at the instantiation point". You can also pass your own comparison:

ADA
procedure Sort_Desc is new Sort (Integer, Positive, Int_Vector, ">");

Generic formal objects (Size : Positive;) pass constants: package Ring is new Buffers (Size => 64);.

A generic package

ADA
generic
   type Element is private;
   Capacity : Positive;
package Bounded_Stack is
   procedure Push (Item : Element);
   function  Pop return Element;
   function  Is_Empty return Boolean;
end Bounded_Stack;

package Int_Stack is new Bounded_Stack (Element => Integer, Capacity => 100);

Each instantiation produces an independent package with its own state. For private stack types rather than a single hidden stack, put type Stack is private; inside the generic package.

flowchart LR
    G["generic package<br/>Bounded_Stack (Element, Capacity)"] -->|"instantiate"| A["Int_Stack<br/>(Integer, 100)"]
    G -->|"instantiate"| B["Name_Stack<br/>(String_Access, 16)"]

One definition, many independent instances, each checked against the same contract.

The standard containers

Ada 2012's Ada.Containers are generic packages you instantiate:

ADA
with Ada.Containers.Vectors;

package Int_Vectors is new Ada.Containers.Vectors
  (Index_Type => Positive, Element_Type => Integer);

V : Int_Vectors.Vector;
...
V.Append (10);
V.Append (20);
for X of V loop
   Put_Line (Integer'Image (X));
end loop;

Also available: Doubly_Linked_Lists, Hashed_Maps, Ordered_Maps, Hashed_Sets, Ordered_Sets, plus bounded and indefinite variants. They manage memory for you.

Stand-in: generics with a C macro and a function pointer

C lacks generics. The usual workarounds are macros that generate type-specific code and void * plus a comparator. This stand-in does both: a macro instantiates swap_int and swap_double (like two instantiations of Swap), and a sort takes a comparison function like the formal "<".

C Stand-in: Swap and Sort by instantiation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A second stand-in is a bounded stack "generic" over its element size, with the capacity as a value parameter like Capacity : Positive. Each instance has its own storage.

C Stand-in: a bounded stack parameterized by capacity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Using private for a formal and then expecting + to work; request the operation as a formal subprogram.
  • Instantiating inside a loop (instantiation is a declaration, not a statement).
  • Forgetting that each instance of a generic package has separate state.
  • Hand-rolling containers instead of using Ada.Containers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does type Item is private; as a generic formal promise?

    A private formal gives the body only assignment and equality, so it can't use anything else without asking.
  2. 2. What creates a usable procedure from a generic one?

    Generic units must be instantiated before use.
  3. 3. How do you give a generic a comparison operation?

    Formal subprograms state the operations that the generic needs.
  4. 4. Where does Ada check a generic body?

    Unlike C++ templates, Ada generics are checked at the definition against their formal contract.

Summary

  • Generic units are parameterized by types, values and subprograms, then instantiated.
  • Formal type kinds state exactly what the body may assume.
  • Each instance of a generic package has independent state.
  • Ada.Containers provides ready-made generic vectors, lists, maps and sets.

Next: Tagged Types and Object-Oriented Programming