70 likes | 181 Views
Department of Computer and Information Science, School of Science, IUPUI. Templates. Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu. Templates. A Template Defines the Content of a Family of Data Types Two Types -- Function and Class Templates .
E N D
Department of Computer and Information Science,School of Science, IUPUI Templates Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu
Templates • A Template Defines the Content of a Family of Data Types • Two Types -- Function and Class Templates
Function Templates • Specifies a Generic Class and Uses this Class in the Function Algorithm • Compiler Creates Appropriate Function Definition Using the Argument Specified During a Function Call Invocation
Function Template -- Example #include<stream.h> //Template Function Definition template <class T> T maximum(T t1, T t2){ if (t1 > t2) {return t1;} else {return t2;} } main(){ int a = 10, b = 15; float c = 20.0, d = 25.5; cout << "Maximum Integer: " << maximum(a, b) << endl; cout << "Maximum Float: " << maximum(c, d) << endl; //ERROR....Parameter Type Mismatch -- No Conversion cout << "Maximum: " << maximum(a, d) << endl; //Explicit Prototype for Forced Conversion float maximum(float, float); cout << "Maximum: " << maximum(a, d) << endl; //FINE }
Class Template • Specifies a Generic Class and Uses it in the Algorithm • Proper Arguments Must be Supplied Before Creating an Instance (or Object) Using the Template Class
Class Template -- Stack Example //A Stack of Arbitrary Elements template <class T> class stack{ T *head; T *tail; int sz; public: stack(int s){head = tail = new T[sz = s];} ~stack(){delete [] head;} void push(T a) {*tail++ = a;} T pop() {return *--tail;} int size() const {return tail - head;} }; main(){ //Stack of 100 Characters stack<char> char_stack(100); char_stack.push('R'); cout << "Stack Size: " << char_stack.size() << endl; //Stack of 50 Integers stack<int> int_stack(50); int_stack.push(10); cout << "Top: " << int_stack.pop() << endl;
Class Template -- Stack Example -- Cont'd OUTPUT WILL BE ------ ---- -- Stack Size: 1 Top: 10