C++ Class Templates
C++ Class Templates
Class templates are one application of templates. Class templates could be used according to the requirements of the programmer. Templates are nothing but shortened generic declarations of similar entities. They are expanded at the compile time.
Examples of some of the in-built class templates are,
Vector, Set, Linked List etc.
Class templates are helpful for classes that are independent of the data type. And like any other function, there could be more than one parameter to a template. On the basis of the number of parameters of a template, they could be single parameters as well as multiple parameters.
A. Single parameter
Syntax for declaring a single parametrized template is,
The example of the vector easily demonstrates how templates are used with a single parameter.
B. Multiple Parameter
Syntax for declaring a multiple parametrized template is,
The difference lies only in the number of parameters we declare inside the template. Consider an example that demonstrates the use of multiple parameters in a class template.
Output
Now, we defined an object obj in myClass to hold a character and an integer data. It could be anything else since both the parameters have been generalized using the template.
C. Default Parameter
C++ Templates have this additional ability to have default parameters. Its ability to have default specifications about the data type, when it receives no arguments from the main is a powerful attribute.
The syntax for making a parameter have a default datatype,
Now, even if the programmer does not specify the type of the data, objects created using this template will automatically make it, of the form <datatype_1, datatype_2>.
Consider an example demonstrating the application of the default parameters,
Output
The template has default defined its parameters as an integer, a float, and a character. Now, if the programmer wishes to change the data types, it must be exclusively mentioned and the object must be defined as it was done in earlier examples.