18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Exceptions 1<strong>95</strong><br />

14.3 Generic stack<br />

The stack illustrated <strong>in</strong> Section 13.5 can be built as a generic package. First, the specification of the package that<br />

conta<strong>in</strong>s the generic components is def<strong>in</strong>ed:<br />

generic<br />

type T is private; --Can specify any type<br />

Max_Stack:<strong>in</strong> Positive := 3; --Has to be typed / not const<br />

package Class_Stack is<br />

type Stack is tagged private;<br />

Stack_Error: exception;<br />

procedure Reset( The:<strong>in</strong> out Stack);<br />

procedure Push( The:<strong>in</strong> out Stack; Item:<strong>in</strong> T );<br />

procedure Pop( The:<strong>in</strong> out Stack; Item:out T );<br />

private<br />

type Stack_Index is new Integer range 0 .. Max_Stack;<br />

subtype Stack_Range is Stack_Index<br />

range 1 .. Stack_Index(Max_Stack);<br />

type Stack_Array is array ( Stack_Range ) of T;<br />

type Stack is tagged record<br />

Elements: Stack_Array; --Array of elements<br />

Tos : Stack_Index := 0; --Index<br />

end record;<br />

end Class_Stack;<br />

Note: The constant Max_Stack must be given a type because it is passed as a generic parameter.<br />

The implementation of the package follows the same strategy as seen <strong>in</strong> Section 13.5.2 except that the<br />

constant that def<strong>in</strong>es the size of the stack is now typed. The body of the package takes this <strong>in</strong>to account by<br />

convert<strong>in</strong>g the constant object Max_Stack <strong>in</strong>to an object of type Stack_Index. The body of the package is<br />

implemented as follows:<br />

package body Class_Stack is<br />

procedure Push( The:<strong>in</strong> out Stack; Item:<strong>in</strong> T ) is<br />

beg<strong>in</strong><br />

if The.Tos /= Stack_Index(Max_Stack) then<br />

The.Tos := The.Tos + 1; --Next element<br />

The.Elements( The.Tos ) := Item; --Move <strong>in</strong><br />

else<br />

raise Stack_Error;<br />

end if;<br />

end Push;<br />

--Failed<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!