140 likes | 359 Views
C++ Templates. Gordon College CPS212. Overview. Templates Definition : a pattern for creating classes or functions as instances of the template at compile time Easily create a large range of related functions or classes Terms: Function template - the blueprint of the related functions
E N D
C++ Templates Gordon College CPS212
Overview • Templates • Definition: a pattern for creating classes or functions as instances of the template at compile time • Easily create a large range of related functions or classes • Terms: • Function template - the blueprint of the related functions • Template instance - a specific function made from a function template (instantiating the template) • Type of programming: • Generic programming • Template metaprogramming
Class Templates • 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; Use Example: Listor< double > doubleListor;
Class Templates • Template class functions • Declared normally, but preceded by template<class T> • Generic data in class listed as type T • Binary scope resolution operator used :: • Template class function definition: template<class T> MyClass< T >::MyClass(int size) { myArray = new T[size]; } • Constructor definition - creates an array of type T
Class Template Example(see template_class_demo) template <typenameT> classstore { public: store(constT& item = T()); TgetValue() const; voidsetValue(constT& item); friend ostream& operator<< (ostream& ostr, conststore<T>& obj) { ostr << "Value = " << obj.value; return ostr; } private: Tvalue; }; Class Declaration
Class Template Example(see template_class_demo) // use an initialization list to assign value template <typenameT> store<T>::store(constT& item): value(item) {} // return the current value template <typenameT> Tstore<T>::getValue() const { returnvalue; } // assign the argument as the new data member value template <typenameT> voidstore<T>::setValue(constT& item) { value = item; } Class Implementation
Class Template Example(see template_class_demo) intmain() { // declare three different types of store objects store<int> intStore(5); store<double> realStore(2.718); store<string> strStore("Template"); cout << "The values stored by the objects are:" << endl; cout << intStore << endl; cout << realStore << endl; cout << strStore << endl; cout << endl; cout << "The concatenation:" << endl; // access current value strStore and concatenate " Class" // update the value in strStore with the new string strStore.setValue( strStore.getValue() + " Class" ); cout << strStore << endl; return 0; } Output The values stored by the objects are: Value = 5 Value = 2.718 Value = Template The concatenation: Value = Template Class Class Usage
Class Templates and Non-type Parameters • Can use non-type parameters (T) in templates • Can have default argument • Treated as const • Example: template< class T = int, int elements > Listor< double, 100 > mostRecentSalesFigures; • Declares object of type: • Listor<100> • Listor< double, 100> • This may appear in the class definition: T stackHolder[ elements ]; //array to hold stack • Creates array at compile time, rather than dynamic allocation at execution time
Function Templates • Defines a pattern for any number of functions whose definitions depend on the template parameters. • Can overload a function template with a non-template function or with other function templates. • Used throughout the STL • sort, copy, for_each, etc.
Function Template Example template <typenameT> voidselectionSort(T arr[], int n) { int smallIndex; // index of smallest element in the sublist int pass, j; T temp; // pass has the range 0 to n-2 for (pass = 0; pass < n-1; pass++) . . . Function Declaration
Function Template Example int itest[20]={4,7,8,9,2,12,3,2,100,34,54,67,54,4,5,87,89,4,5,23}; string stest[10]={"this", "is", "a", "test", "I", "hope", "it", "works", "It", "worked"}; for(int i = 0;i<20;i++) cout<<" "<<itest[i]; cout<<endl; for(int i = 0;i<10;i++) cout<<" "<<stest[i]; cout<<endl; cout << "SORTED" <<endl; selectionSort(itest, 20); for(int i = 0;i<20;i++) cout<<" "<<itest[i]; cout<<endl; selectionSort(stest, 10); for(int i = 0;i<10;i++) cout<<" "<<stest[i]; cout<<endl; output 4 7 8 9 2 12 3 2 100 34 54 67 54 4 5 87 89 4 5 23 this is a test I hope it works It worked SORTED 2 2 3 4 4 4 5 5 7 8 9 12 23 34 54 54 67 87 89 100 I It a hope is it test this worked works Function Usage
Operator Templates • Create operator template in the same manner as function templates • Rules for deducing argument types apply • Example: Template<typename T> Bigint operator+(const Bingint& x, const T& y); Bigint a; a = a + 42; //argument type deduction a = operator+<long>(a,42); //explicit argument type
Operator Template Example template <classT> classArray { private: T* pType; intitsSize; public: Array(int itsSize = DefaultSize); Array(constArray &rhs); ~Array(){delete [] pType;} Array& operator=(constArray&); T& operator[](int offset){ returnpType[offset];} constT& operator[](int offset) const { returnpType[offset];} intGetSize() const {returnitsSize;} }; Operator Declaration
Operator Template Example Array<int> theArray; Array<Animal> theZoo; Animal *pAnimal; for(int i=0; i<theArray.GetSize(); i++) { theArray[i] = i*2; pAnimal = new Animal(i*3); theZoo[i] = *pAnimal; delete pAnimal; } for(int j=0; j<theArray.GetSize(); j++) { cout << "theArray[" << j << "]: "; cout << theArray[j] << ”\t\t"; cout << "theZoo[" << j << "]: "; cout << theZoo[j] << endl; } Operator usage: see template_operator_zoo