Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Templates is a concept which enable us to define generic classes and functions and thus support for generic programming .
A short History
` ` `
Templates are not the feature of original c++ It was added in 1994 by Bjarne Stroustrup The 1st thought of generic programming was introduced by the nephew of Babage in time of developing the Language ADA in 1983.
Class Templates: ` Allow type-specific versions of generic classes Format: template <class T> class ClassName{ definition }
Need not use "T", any identifier will work To create an object of the class, type ClassName< type > myObject; Example: Stack< double > doubleStack;
Example: #include<iostream.h> template<class T1,class T2> class Test { T1 a; T2 b; Public: Test(T1 x,T2 y) { a=x; b=y; }
Function Template
Function Template :
`
A function template is not an actual function, but instead is a pattern for what could become a function
Format: template<class t> return_type function_name (arguments of type T) { //body of function //with type t //when ever appropriate //. }
Output: m and n before swap:100 200 m and n after swap:200 100 a and b before swap:11.22 33.439999 a and b after swap:33.439999 11.22
Advantages
` ` `
Easily create a large range of related functions or classes Function template - the blueprint of the related functions Template function - a specific function made from a function template
Disadvantage
Creates large range of codes to handle all kind of situations(Exceptions).Which may cause allocation of extra memory space.
Conclusion
The generic programming is the highest level of any programming language though it creates a lot of extra codes which sometime may cause some unnecessary memory blockage. In my opinion its a great feature and we can use it as we need . The flexibility of codes reaches the highest standard by the use of templates.
Thank you