This chapter introduces you to two features of Ada that make the language extremely useful for developing reusable software components: unconstrained array types and generics. An unconstrained array type is one declared in such a way that the bounds of the array are not specified in the type declaration; rather, they are supplied only when a variable of the type is declared. Many arrays of the same number of dimensions but differing sizes can be declared from the same type definition. Moreover, subprograms can be written which accept these arrays as parameters and work with them without knowing their sizes in advance. This is extremely helpful in writing general-purpose programs such as sorts and numerical algorithms.
As it happens, we have been using an unconstrained array type all along in this
book: Ada's String
type is one of these, predefined in
Standard
. In this chapter you will learn how to define and use
unconstrained array types of your own. Understanding unconstrained array types
is an important part of understanding how to use generics well; that is why the
two subjects are together in this chapter.
A generic component (package or subprogram) is one that is parametrized at the level of the types it works with. There are generic formal and actual parameters, just like the "normal" ones we use with subprograms and variant records. A generic component can be instantiated or "tailored" to work with a specific type. This means that a very general program or package can be written, whose code is independent of the type it manipulates. Versions of it can be created with a single statement in each case, to handle many different types.
You have been using generic units from the start in this book. You tailored
Ada.Text_IO.Enumeration_IO
for different enumeration types, most
recently Dates.Months
in Chapter 10. Also, in Chapter 7 we
tailored Ada.Numeric.Discrete_Random
for a range of random
numbers. This chapter shows you how to create your own generics and tailor them
for many interesting purposes.
Through the careful design of generic units, an entire industry of reusable, tailorable, software components can be built up and used for a wide range of applications. Indeed, several small companies have been quite successful doing exactly that.
Copyright © 1996 by Addison-Wesley Publishing Company, Inc.