1 / 14

C++ Templates

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

aliya
Télécharger la présentation

C++ Templates

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Templates Gordon College CPS212

  2. 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

  3. 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;

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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.

  10. 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

  11. 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

  12. 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

  13. 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

  14. 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

More Related