Lecture 11
Lecture 11
#include <iostream> #include <string> using namespace std; template <class Type> Type larger(Type x, Type y) int main() { cout << Larger of 5 and 6 = << larger(5, 6) << endl; cout << Larger of A and B = << larger(A, B) << endl; cout << Larger of 5.6 and 3.2 = << larger(5.6, 3.2) << endl; string str1 = Hello; string str2 = Happy; cout << Larger of << str1 << and << str2 << = << larger(str1, str2) << endl; return 0; } template <class Type> Type larger (Type x, Type y) { if (x >=y) return x; The type of data. Dont worry about what the word class means. This is a function template declaration. The function template is called larger. (Alternatively, we can have a class declaration.)
else return y; }
Revision on Classes
Let us define a class that performs various operation on a list. class intListType { public: bool isEmpty (); bool isFull (); int search (int searchItem); void insert (int newItem); void remove (int removeItem); void printList (); intListType (); private: int list [1000]; int length; }; Following this we can now define the member functions of class intListType. bool intListType::isEmpty () { } bool intListType::isFull () Returns the position in the list.
Class Templates
template <class elemType> class listType { public: bool isEmpty (); bool isFull (); void search (const elemType& searchItem, bool& found); void insert (const elemType& newElement); void remove (const elemType& removeElement); void destroyList (); void printList (); listType (); private: elemType list [100]; int length; }; Following this we can now define the member functions of class template listType. template<class elemType> bool listType<elemType>::isEmpty () {
} template<class elemType> bool listType<elemType>::isEmpty () { } To create a list of integers we use: listType<int> intList; To create a list of strings we use: listType<string> stringList;