Download Understanding C++ Templates: Function/Class Templates, Swap Function, Sorting Algorithm and more Study notes Data Structures and Algorithms in PDF only on Docsity! Chapter 3 Templates Ken Nguyen Spring 2002 3.1 What is a Template • A mechanism for writing routines that work for arbitrary types w/o knowing these types, i.e. type independent • Most likely be seen in generic algorithm implementations, i.e. sorting & searching. int main(){ int x =5, y = 7; double a = 2, b = 4; swap (x,y); // swap(int,int) swap(x,y); //reuse previous instantiation swap(a,b); //swap(double, double) //swap(x, b); // illegal: no match return 0; } // figure 3.3 3.3 Sorting Function Template template <class Comparable> void insertionSort(vector<Comparable> &a){ for(int p = 1; p < a.size(); p++){ Comparable tmp = a[p]; int j; for(j = p; j > 0 && tmp < a[j-1]; j++) a[j] = a [j –1]; a[j] = tmp; } } • The given insertionSort routine works for double, int, float but not char*, (primitive string), because operator “=” and “<” are undefined. • sorting demo int main() { MemoryCell<int> m; m.write(5); cout<<“Cell contents are ” <<m.read()<<endl; return 0; } When the interface is separated from the implementation, all members function should be implemented as template functions #include “MemoryCell.h” template <class Object> MemoryCell<Object>::MemoryCell (const Object & initVal) :storedValue(initVal){} template<class Object> const Object & MemoryCell<Object>::read() const {return storedValue;} template <class Object> void MemoryCell<Object>::write( const Object & x) {storedValue = x;} // figure 3.11 template<class Object> class MemoryCell { public: explicit MemoryCell(const Object & initVal = Object()); const Object & read() const; const write(const Object & x); private: Object storedValue; };// figure 3.10 template<class object> class ClassName{ public: //public members private: //private member };// typical template interface template <class object> ReturnType ClassName<object>::memberName(parameterList) /*const*/ { // member body } // typical member implementation 3.6 Fancy Templates • Multiple template parameters template <class keyType, class valueType> Class Map{ . . . }; Ex: map<string,int> zipCodes; Note: class “map” is in STL Default Template Parameters template <class keyType, class valueType = string> Class Map{ . . . }; Map<int, int> m1; // keyType = int, valueType = int Map<int> m2; // keyType = int, valueType = string Default template parameters are widely used in STL Note: some compilers do not support default template parameters • typename : a new keyword can be used instead of class template <typename Object> class memoryCell { . . . };