Generic Programming

Read this text, which discusses the basics of generic programming and relates it to different languages.

3. Programming language support for genericity

3.3. Advantages and limitations

The language syntax allows precise specification of constraints on generic formal parameters. For example, it is possible to specify that a generic formal type will only accept a modular type as the actual. It is also possible to express constraints between generic formal parameters; for example:

 generic

    type Index_Type is (<>); -- must be a discrete type

    type Element_Type is private; -- can be any nonlimited type

    type Array_Type is array (Index_Type range <>) of Element_Type;

In this example, Array_Type is constrained by both Index_Type and Element_Type. When instantiating the unit, the programmer must pass an actual array type that satisfies these constraints.

The disadvantage of this fine-grained control is a complicated syntax, but, because all generic formal parameters are completely defined in the specification, the compiler can instantiate generics without looking at the body of the generic.

Unlike C++, Ada does not allow specialised generic instances, and requires that all generics be instantiated explicitly. These rules have several consequences:

  • the compiler can implement shared generics: the object code for a generic unit can be shared between all instances (unless the programmer requests inlining of subprograms, of course). As further consequences:
    • there is no possibility of code bloat (code bloat is common in C++ and requires special care, as explained below).
    • it is possible to instantiate generics at run-time, as well as at compile time, since no new object code is required for a new instance.
    • actual objects corresponding to a generic formal object are always considered to be non-static inside the generic; see Generic formal objects in the Wikibook for details and consequences.
  • all instances of a generic being exactly the same, it is easier to review and understand programs written by others; there are no "special cases" to take into account.
  • all instantiations being explicit, there are no hidden instantiations that might make it difficult to understand the program.
  • Ada does not permit "template metaprogramming", because it does not allow specialisations.