Bài giảng Lập trình hướng đối tượng - Chương 5: Templates

A function template is a pattern for creating a family of similar functions.

 

If you need two or more functions with identical behaviour that differ only in their parameter types, you can write a function template that the compiler will use to generate the definitions of the actual functions.

 

ppt40 trang | Chuyên mục: Lập Trình Hướng Đối Tượng | Chia sẻ: dkS00TYs | Lượt xem: 1762 | Lượt tải: 2download
Tóm tắt nội dung Bài giảng Lập trình hướng đối tượng - Chương 5: Templates, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
Chương 5 TEMPLATES Tài liệu đọc Templates Function templates Class templates Inheriting Template Classes Templates According to the dictionary, a template is a pattern or guide used to replicate an object e.g. a biscuit cutter. Function templates A function template is a pattern for creating a family of similar functions. If you need two or more functions with identical behaviour that differ only in their parameter types, you can write a function template that the compiler will use to generate the definitions of the actual functions. Function templates A function template has the general form template returnType functionName(parameterList) { // Body of the function } Function templates (I) The keyword template indicates that what follows is a function template, not an actual function. The notation is the template parameter list. Function templates (II) The keyword class indicates that T is a generic type i.e. a placeholder for a data type used by the function. The identifier T appears throughout the function definition wherever this type needs to be written. Generated functions When the function template is called, the compiler deduces the type of the actual argument and substitutes it for the generic type T, creating what is known as a generated function. The act of generating a function is referred to as instantiating the template. template void swap ( T& first, T& second) { T temporary = first; first = second; second = temporary; } Example 1 int main(void) { int x = 1 , y = 2 ; char a = 'A‘ ; char b = ‘B’; swap(x, y); swap(a, b); // ... return 0; } Example 1 .. 2 Explicitly specifying the type The actual type that is substituted for a template's generic type can be explicitly specified in a function call by writing it between angle brackets immediately after the function name. int i = 11; int j = 22; swap(i, j); The type that is explicitly specified takes precedence over the type that is deduced by the compiler. Instantiating with different types You cannot instantiate a function template if the types of arguments in your function call fail to match the template's expectations. int r = 3; double s = 4.4; swap(r, s); // Error Mixing generic types and actual types A function template's parameter list may contain a mixture of generic and actual types. template void rotate ( T array[ ], int size) { T temporary = array[0]; for (int i = 0; i void swap(char* first, char* second) { int maxLength; // Length of longest string // Find length of longest string if (strlen(first) >= strlen(second)) maxLength = strlen(first); else maxLength = strlen(second); Example 2 // Allocate memory for temporary string char* temporary = new char [maxLength + 1]; assert(temporary != 0); // Exchange strings strcpy(temporary, first); strcpy(first, second); strcpy(second, temporary); // Delete temporary string delete [ ] temporary; } Example 2 .. 2 Class templates A class template is a pattern for creating a family of similar classes.  If you need two or more classes with identical members that differ only in their parameter types, you can write a class template that the compiler will use to generate the definitions of the actual classes. Class templates A class template has the general form template class ClassName { // ... }; The keyword template indicates that what follows is a class template, not an actual class. Class templates The notation is the template parameter list. The keyword class indicates that T is generic type i.e. a placeholder for a data type used by the class. The identifier T appears throughout the class definition wherever this type needs to be written. Generated classes When an object of a class template is declared, the compiler instantiates the template, creating what is known as a generated class. The declaration of a generated class has the general form className objectName; Member functions of a generated class The member functions of a class template are function templates, and must be written as such. Each member function definition that appears outside the class definition must begin with the prefix template Member functions of a generated class In addition, the member function's name must be qualified with the parameterised class name ClassName followed by the scope resolution operator. // Header file for the Stack class, stack.h #include const int size = 100; template class Stack { private: T array[size]; int numItems; Example 3 (stack.h) public: // Constructor Stack() : numItems(0) { } // Pushes an item onto the stack void push(T item); // Pops an item off the stack T pop(); }; Example 3 (stack.h) .. 2 // Push item onto stack template void Stack :: push( T item) { if (numItems == size) { cout T Stack :: pop() { if (numItems == 0) { cout int main(void) { Stack intStack; Stack charStack; intStack.push(10); charStack.push('a'); cout class Matrix { // ... // Friend of all instances of Matrix friend void grid(); // Friend of a specific instance of Matrix friend ostream& operator& op) }; Example 4 Inheriting Template Classes Template classes can be inherited according to the standard inheritance guidelines. Inheritance can use two approaches (both very common): The derived class is not a template. The actual type will be defined when inheriting. 	class ExtendedIntArray : public Array The derived class is by itself a template class. No need to specify the type when inheriting. 	templateclass ExtendedArray : public Array Introduction copyrights © Elhanan Borenstein Inheriting Template Classes If while inheriting the template class, we specify all the parameters of the template class, we will actually create a new regular (non-template) class. Example: ExtendedIntArray A Class Derived from Template Class copyrights © Elhanan Borenstein Inheriting Template Classes Example: extintarray.cpp Example: temptemp.cpp A Template Class Derived from a Template Class copyrights © Elhanan Borenstein Exercise 1 Implement a generic Find() function, which gets: a pointer to the beginning of an array a pointer to the end of an array the value to search for The function returns the address of the first items in the array that is equal to the given value or the address of one location after the last item if the value was not found. copyrights © Elhanan Borenstein template T* Find(T* begin, T* end, T value) { while (begin != end) if (*begin == value) 	return begin; else 	begin++; return begin; } void main() { int array[ ] = {3,2,5,7,2,8,11}; int* j = Find (array, array + 6, 7); } Exercise 2.1 Implement a class called Sqr which will include only one thing: an overloading of the operator () which will get as a parameter T& and will assign to it its square value. copyrights © Elhanan Borenstein class Sqr { public: template void operator() (T& t) { 	t = t*t; } }; void main() { Sqr MySqrMachine; int i = 2; float f = 3.25; MySqrMachine(i); MySqrMachine(f); } Exercise 2.2 Implement a general DoIt fucntion which gets: a pointer to the beginning of an array a pointer to the end of an array A reference to an object The function should go over all elements of the array and send each element to the () operator of the object it got. copyrights © Elhanan Borenstein template void DoIt(T* begin, T* end, G& Obj) { while (begin != end) { obj(*begin); begin++; } } Exercise 2.all Putting it all together… copyrights © Elhanan Borenstein class Sqr { public: template void operator() (T& t) { 	t = t*t; } }; void main() { int array[ ] = {1,5,7,8,3,2,9,2,12}; DoIt(array, array + 8, Sqr()); } template void DoIt(T* begin, T* end, G& Obj) { while (begin != end) { obj(*begin); begin++; } } AMAZING !!!! DoIt() is completely general: 	It doesn’t know the array type. 	It doesn’t know the action it is doing Food for Thoughts Imagine a template class We wish that all instances of MyClass will be friends... friend MyClass ??? friend MyClass ???(and than template) What if a regular (non-template) class A wishes to give friendship to all instances of MyClass? What’s the meaning of all that??? copyrights © Elhanan Borenstein template class MyClass { T t; … }; Hỏi và Đáp 

File đính kèm:

  • pptBài giảng Lập trình hướng đối tượng - Chương 5 Templates.ppt
Tài liệu liên quan