Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 159.234LECTURE 17 159.234 LECTURE 17 Templates 19 An abstract recipe for producing concrete code.

Similar presentations


Presentation on theme: "1 159.234LECTURE 17 159.234 LECTURE 17 Templates 19 An abstract recipe for producing concrete code."— Presentation transcript:

1 1 159.234LECTURE 17 159.234 LECTURE 17 Templates 19 An abstract recipe for producing concrete code.

2 2Templates Function Overloading function overloading allows the same function to act on different argument types: 19 int max(int a, int b) { if (a > b) return a; else return b; } float max(float x, float y) { if (x > y) return x; else return y; } This is useful, but we are duplicating code! both arguments are of the same type

3 3Templates Function Templates Templates let us write the two functions with no duplication: 19 template T max(T x, T y) { if (x > y) return x; else return y; } The compiler generates code for us when it comes across statements such as: i = max(j, k); Template parameters are place holders for types and classes. The use of the word class here means “any type” For each call, the compiler generates the complete function, replacing the type parameter with the type or class to which the arguments belong. Type parameter

4 4Templates Function Templates More generally, a template may have several type parameters 19 template Template parameters are place holders for types and classes. Type parameters

5 5Templates It also works for user defined types: 19 Date d1,d2,d3; d3 = max(d1,d2); operator> Provided that as we have an operator> for the Date class. Function templates can themselves be overloaded: S template S T max(T x, S y) { if (x > y) return x; else return y; } > We can now compare an object with any other object as long as > is defined. S = T In fact this version can replace the previous one (it is the special case when S = T)

6 6Templates Function templates are a of function overloading. Function templates are a direct generalization of function overloading. Function templates share source code among families of functions. Function templates share source code among structurally similar families of functions. Templates can also be used with classes. We can create that handle different types of data. We can create generic classes that handle different types of data. 19

7 7 Class Templates 19 Templates are instantiated at compile time, and so, values passed to non-type parameters must be constants. Like function templates, a class template may have several type parameters. Moreover, some of them may be ordinary non-type parameters. template Non-type parameter Class template with multiple type of parameters

8 8 Class Templates 19 parameterized types Class templates are sometimes called parameterized types. template class X {}; int main() { X x1; //OK const int n=44; X x2; //OK int m=66; m X x3; //error! – m must be a constant } Non-type parameter Example

9 9 Class Templates Instantiating Class templates 19 The square function in this example would be handled in the same way. T template class X{ T T square(T t) { return t*t; } }; Member functions of a class template are themselves function templates with the same template header as their class. T template TT T square(T t) { return t*t; } Template function Member function of a class Template

10 10 Class Templates Instantiating Class templates 19 T It is instantiated by the compiler, replacing the template parameter T with the type passed to it. X x; Consider the class declaration: Class X_short{ short square(short t) {return t*t;} }; X_short x; Except that your compiler might assign a different name for the class other than X_short. Therefore, the compiler generates the following class and object *

11 11 Class Templates Instantiating Class templates 19 instantiating templates The facility that C++ provides for instantiating templates is one of its major features and one that distinguishes it from most other programming languages. mechanism for code generation As a mechanism for code generation, it allows for substantial improvements in programming efficiency.

12 12Templates For the Vector class - we may want Vectors of integer, float, Date, etc. Without templates, we have to create different vectors for each of them, with templates we can create a single generic vector: 19 T template class Vector { public: Vector(int n=100); //constructor T T& operator[](int i); //range checked! TT Vector & operator=(Vector &v); private: T T* p; int size; }; Example

13 13TemplatesConstructor: 19 template Vector ::Vector(int n=100) : size(n) { assert(n>0); p = new T[size]; assert(p != NULL); }

14 14Templates operator[ ] 19 template T& Vector ::operator[](int i) { assert((i>=0) && (i<size)); return p[i]; }

15 15Templates operator = 19 template Vector & Vector ::operator=(Vector &v) { assert(size == v.size); for (int i = 0; i<size; i++) { p[i] = v.p[i]; } return *this; }

16 16Templates Using a Template Class Finally, this is how we use a template class: 19 int main() { Vector m(100); Vector d(200); m[3] = 34;... }

17 17TemplatesExample STACKS 19 A stack ADT is a LIFO type. For the stack class we may want stacks of integer, float, Date etc without templates we have to create stacks for each of them, with templates we can create generic stacks with templates we can create generic stacks See also OOP-11 Slide presentation about STACKS

18 18 Sample Program: ch_stack See ch_stack.cpp 99.. 2 1 0 s Top = -1 Max_len=100 Data members 99.. 2 1 0 T hTsi Str Push Increment Top Put character into element of stack pointed to by Top Top Initially,

19 19TemplatesExample Declaration for a Stack of doubles 19 class class StackD{public: StackD(int = 10) ; ~StackD() { delete [] stackPtr ; } int push(const double &); int pop(double&); // pop an element off the stack int isEmpty()const { return top == -1 ; } int isFull() const { return top == size - 1 ; }private: int size ; // Number of elements on stack int top ; double* stackPtr ; } ;

20 20TemplatesExample Class Definition 19 //constructor with the default size 10 StackD::StackD(int s){ size = s > 0 && s < 1000 ? s : 10 ; top = -1 ; // initialize stack stackPtr = new double[size] ; } // push an element onto the Stack int StackD::push(const double& item){ if (!isFull()){ stackPtr[++top] = item ; return 1; // push successful } return 0; // push unsuccessful }

21 21Templates Class Definition Pop 19 // pop an element off the Stack int StackD::pop(double& popValue){ if (!isEmpty()){ popValue = stackPtr[top--] ; return 1 ; // pop successful } return 0 ; // pop unsuccessful }

22 22 int main(){ StackD fs(5) ; double f = 1.1 ; cout << "Pushing elements onto fs" << endl ; while (fs.push(f)){ cout << f << ' ' ; f += 1.1 ; } cout << endl << "Stack Full." << endl << endl << "Popping elements from fs" << endl ; while (fs.pop(f)) cout << f << ' ' ; cout << endl << "Stack Empty" << endl ; }Templates Using the Class StackD

23 23 template class StackT{ public: StackT(int = 10) ; ~StackT() { delete [] stackPtr ; } int push(const T&); int pop(T&) ; int isEmpty()const { return top == -1 ; } int isFull() const { return top == size - 1 ; } private: int size ; int top ; T* stackPtr ; } ; Class Templates Example http://www.is.pku.edu.cn/~qzy/cpp/vc-stl/templates.htm

24 24 template StackT ::StackT(int s){ size = s > 0 && s < 1000 ? s : 10 ; top = -1 ; // initialize stack stackPtr = new T[size] ; } Class Templates Example

25 25 template int StackT ::push(const T& item){ if (!isFull()){ stackPtr[++top] = item ; return 1 ; // push successful } return 0 ; // push unsuccessful } template int StackT ::pop(T& popValue) { if (!isEmpty()){ popValue = stackPtr[top--] ; return 1 ; // pop successful } return 0 ; // pop unsuccessful } Class Templates Example

26 26 int main(){ typedef StackT FloatStack ; typedef StackT IntStack ; FloatStack fs(5) ; float f = 1.1 ; cout << "Pushing elements onto fs" << endl ; while (fs.push(f)){ cout << f << ' ' ; f += 1.1 ; } //more code here… } Class Templates Using the Class StackD

27 27 Macros present the possibility of having side effects and does not usually have type checking. #define SQ(A) ((A)*(A)) template T square (T x){ return x*x; } Templates vs. Macros http://www.ebyte.it/library/codesnippets/WritingCppMacros.html

28 28 int main(){ int a = 7; cout<<square(a++)<<endl; cout<<"and a is "<<a<<endl; cout <<SQ(a++)<<endl; cout<<"and a is "<<a<<endl; } /*output: 49 and a is 8 64 and a is 10 */ Templates vs. Macros

29 29 1. Not using template when defining member function for class templates. 2. Not using the generic type for parameters/variables. 3. Not placing class, before every formal type parameter. Correct: template If a template is invoked with a user defined class type and that template uses operators (==, +, <=) with objects of that class type, then those operators must be overloaded. Common Errors with Templates

30 30 A large collection of reusable components. The key components of the STL -- containers are data structures created using templates. A container is an object that contain objects. Using STL can save considerable time and effort, and result in higher quality programs. Standard Template Library (STL)

31 31 templates C++ uses templates to provide generic programming. Templates are one of C++’s capabilities for software reuse. The same code is used with different types, where the type is a parameter of the code body. OOP does not require templates, its just a C++ feature.Summary

32 32Templates When do we allow a Tank to jump? Q 17

33 33 Jumping over the Ledge * You will have to check if the Tank can actually jump first, before allowing it to jump on screen. So even if the user presses the key combination that instructs the Tank to jump e.g. (Ctrl+Shift+Left) to jump left, or (Ctrl+Shift+Right) to jump right The tank should be coming from the ground or off the ledge, in order to jump.


Download ppt "1 159.234LECTURE 17 159.234 LECTURE 17 Templates 19 An abstract recipe for producing concrete code."

Similar presentations


Ads by Google