Class Templates to a stack

  • As we have just seen, a class template definition looks like a regular class definition, except it is prefixed by the keyword template.
  • For example, the following slide has definition of a class template for a Stack.

  • Class Templates

  • T is a type parameter and it can be any type. For example, Stack<Token>, where Token is a user defined class. T does not have to be a class type as implied by the keyword class. For example, Stack<int> and Stack<Message*> are valid instantiations, even though int and Message* are not "classes".
  • While implementing class template member functions, the definitions are prefixed by the keyword template.




    • Using a class template is easy. Create the required classes by plugging in the actual type for the type parameters.
    • This process is commonly known as "Instantiating a class". Here is a sample driver class that uses the Stack class template.


    Output

    Pushing elements onto fs
    1.1 2.2 3.3 4.4 5.5
    Stack Full.
    Popping elements from fs
    5.5 4.4 3.3 2.2 1.1
    Stack Empty
    Pushing elements onto is
    12345678910
    Stack Full
    Popping elements from is
    10987654321
    Stack Empty

    Templates<< Previous
    Next >> Function Templates

    Our aim is to provide information to the knowledge seekers. 


    comments powered by Disqus


    Footer1