Template is the basis of generic programming, generic programming in a way that is independent of any particular type of writing code. Template function is to create a generic class or blueprint or formula. Library containers, iterators, and algorithms for example, are examples of generic programming, they all use the concept of templates. Each container has a single definition, such as vectors, it can be defined in many different types of vectors, such as Vector < int > or Vector < String >.
As shown in general form template function is defined as follows: Template < class type> func- RET-type name (Parameter List) { // main function } Here, type is the data type used by functions placeholder name. The name can be used in the function definition.
#include <iostream> #include <string> using namespace std; template <typename T> inline T const& Max (T const& a, T const& b) { return a < b ? b:a; } int main () { int i = 39; int j = 20; cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return 0; }
The definition of a class template. The general form of the generic class declaration is as follows: Template < class type> class class - {name . . . } Here, type is the placeholder type name, it can be specified when the class is instantiated. A comma-separated list can be used to define a plurality of generic data types.
The following example defines a class Stack <> , and a generic method to implement the elements of the stack pop operations: #include <the iostream> #include <Vector> #include <the cstdlib> #include < String > #include <stdexcept > the using namespace STD; Template < class T> class stack { Private : Vector <T> the elems; // element public : void Push (T const &); // stack void POP (); // a stack Top T () const ; // return the top element BOOL empty () const { // If it is empty it returns true. return elems.empty (); } }; Template < class T> void Stack <T> :: Push (T const & elem) { // append a copy of the incoming elements elems.push_back (elem); } Template < class T > void Stack <T> :: POP () { IF (elems.empty ()) { the throw out_of_range ( "Stack <> :: POP (): Stack empty " ); } // remove the last element elems.pop_back (); } Template < class T> T Stack <T> :: Top () const { IF (elems.empty ()) { the throw out_of_range ( " Stack <> :: Top (): Stack empty " ); } // returns a copy of the last element return elems.back (); } int main () { the try { Stack < int > IntStack; //int type stack Stack < string > stringStack; // string type stack // operations of type int stack intStack.push ( . 7 ); COUT << intStack.top () << endl; // operation type string stack stringStack .push ( " Hello " ); COUT << stringStack.top () << STD :: endl; stringStack.pop (); stringStack.pop (); } the catch (Exception const & EX) { cerr, << " Exception:" << ex.what() <<endl; return -1; } }