In contrast to the sample implementations of a stack in
previous chapters, you can also implement a stack by using a fixed-size array
for the elements. An advantage of this method is that the memory management
overhead, whether performed by you or by a standard container, is avoided.
However, determining the best size for such a stack can be challenging. The
smaller the size you specify, the more likely it is that the stack will get
full. The larger the size you specify, the more likely it is that memory will be
reserved unnecessarily. A good solution is to let the user of the stack specify
the size of the array as the maximum size needed for stack elements.
To do this, define the size as a template parameter:
The new second template parameter, MAXSIZE, is of type
int. It specifies the size of the array of stack elements:
In addition, it is used in push() to check whether the
stack is full:
To use this class template you have to specify both the element
type and the maximum size:
Note that each template instantiation is its own type. Thus,
int20Stack and int40Stack are two different types, and no
implicit or explicit type conversion between them is defined. Thus, one cannot
be used instead of the other, and you cannot assign one to the other.
Again, default values for the template parameters can be
specified:
However, from a perspective of good design, this may not be
appropriate in this example. Default values should be intuitively correct. But
neither type int nor a maximum size of 100 seems intuitive for a
general stack type. Thus, it is better when the programmer has to specify both
values explicitly so that these two attributes are always documented during a
declaration.
-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------
- Complete Tutorial of C++ Template's
- Standard Template Library Tutorial
- Inter Process Communication Tutorial
- Advance Programming in C & C++
-----------------------------------------------------------------
No comments:
Post a Comment