Just like function templates, we can also make and use class templates in our program. With the help of class templates, a whole class could be made generic. Each function declared within the class is a template function by default. Class templates behave much like the function templates though there is a lot more to be associated and understood with them. Class templates can also be specialized like specializing function templates. For this article, I would explain only how to make a simple class, a template class.
Posts Tagged ‘templates’
A technique quite frequently employed in Object Oriented Paradigm and otherwise is known as Generic Programming. Generic Programming is a concept using which you a user can write a code which works well for many data types. In other words, it is type independent programming. A function made generic does not need to know what kind of data type it is receiving. Generic programming is made possible through a feature known as templates. Templates allow functions and classes to operate with these generic or types. I shall explain you why we need templates and how do we employ them.
We have been discussing templates in detail for over two weeks. First we explored function templates with a single parameter, then with multiple parameters and also learnt how to specialize template functions. Currently we are exploring class templates. Today we shall see how we can specialize class templates for a particular data type. They are specialized like function templates and behave identically as well but they are declared with a different syntax.
Templates are a very powerful tool in programming. They constitute the so called feature of Type Independent or Generic Programming. We have seen that using templates with multiple parameters or a single parameter, we can save our time and energy and write a code in a generic manner instead of writing it for each and every data type. However, as a thing becomes powerful, there are also certain potential dangers associated with it. One such scenario arises with templates quite frequently while its solution lies in template specialization. This type of specialization s known as Complete Specialization.
We have learnt that Templates in C are a very powerful feature. They constitute the concept of Generic Programming or Type Independent Programming. Last time, we saw templates that have one parameter or one generic type. They have the limitation that only one type of data type can be processed at a time. To solve that problem, we use templates with more than one type of parameters. Such multiple type templates allow more than one type of data types to be process at once.