Templates are also widely used for classes. For example, the Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions.
The syntax of template classes is similar to template functions, with keyword template and the template parameters before the class name. Since that the class name of a template class is composed of the template name and the template parameter, wherever a template class appears should the parameters be added as well. For convenience, constructors and destructors can omit template parameters.
A template version of our MyStack class is shown as follow:
The keyword template only play a role within the scope of the class. So if we want to implement member functions outside the class, keyword template should be reused again.
Then we can use our self-defined fancy stack in the main function. When the template class is used, the compiler instantiate a copy of it with the type we choose. But unlike template functions, this instantiation is selective, which means only those methods being called are instantiated. This approach decreases the amount of the code text.
Templates can also have default parameters as well. In the following case, if we don't specify the type when using MyStack, the type name is int by default.