Need For Templates
A template is a technique that allows a single function or class to work with different data types. Using a template, we can create a single function that can process any type of data; that is, the formal arguments of a template function are of template (generic) type. They can accept data of any type, such as int, float, and long. Thus, a single function can be used to accept values of a different data type. Figures (Working of non-template function) and (Working of template function) clear the difference between the non-template function and template function. Usually, we overload a function when we need to handle different data types. This approach increases the program size. The disadvantages are that not only the program length is increased but also more local variables are created in the memory. A template safely overcomes all the limitations occurring during the overloading function and allows better flexibility to the program. The portability provided by a template mechanism can be extended to classes. The following sections describe the use of templates in different concepts of C++ programming. Let us understand the process of the declaration of a template.