.Open CSci202 Computer Science II, Session 10, Template Functions (previous): Polymorphism .See http://www/dick/cs202/09.html . Preparation -- 14 Templates 756 14.1 Introduction 757 14.2 Function Templates 758 14.3 Overloading Function Templates 761 14.4 Class Templates 761 14.5 Nontype Parameters and Default Types for Class Templates 768 14.6 Notes on Templates and Inheritance 769 14.7 Notes on Templates and Friends 769 14.8 Notes on Templates and static Members 770 14.9 Wrap-Up 771 . Notes on Templates .See ./templates.html . Templates in the UML .See ./uml1a.html#Templates . Assigned Work Due -- one Question Hand in your questions, doubts and surprises. With page numbers and name. . What is the difference between templates and vectors Vectors are data. Templates are program. However, the "vector" class in C++ is a special class template and this is why we write .As_is vector counters; to construct a collection of ints. It might be defined as .As_is template vector; inside the library. Actually it is more complex and has another parameter that few people ever use. . What should you keep in mind when writing a template function .List You can use the template parameters/arguments as variables. You don't know what the actual types of the data is -- keep to simple overloaded operations. You are writing a function -- all the normal thinking is needed. .Close.List . What is the purpose of nontype parameters The commonest use of a nontype parameter is to give the (fixed) size of some data storage: .As_is template class Buffer {..... char b[size]; ....}; . What is the difference between a function and a class template A function template describes a family of functions with the same name, different types of data, and the same computations. A class template defines a family of classes. For a given set of actual parameters you get the right kind of attributes and functions for the actual class. For example .As_is template class Buffer {..... Data b[size]; ....}; describes character buffers .As_is Buffer and Unicode buffers .As_is Buffer and so on... . Templates a preprogrammed actions does it help software react in new ways Templates are not that much help since they are done by the compiler. Polymorphism lets a program reconfigures itself as it runs! . How do you call a template function Just like a normal function. Just make sure you supply data of the right types. . Do all templates start with template Pretty much. Only caveat -- functions inside a template class as also templated. . Do templates speed up the program or the programmer The programmer. . Are template classes used for other things than stacks YES! vectors, lists, heaps, trees, queues, arrays, buffers, priority-queues, red-black trees, hash tables, deques, ..... . Can macros be used in C++ Macros were a part of the C language. C++ inheritted them. . Macros described Macros look like this .As_is #define identifier replacement .As_is #define identifier(arguments) replacement The compiler has several passes through the program in the first pass -- the .Key pre-processor -- it handles all the "pre-processor directives" -- marked by a "#". It stores the definitions (#define). If it sees an identifier from the first kind of define it removes it and inserts the replacement text. It does this even if the result is rubbish or worse surprising. If the pre-processor sees an identifier from the second form and it is called like this .As_is identifier(actualArguments) then it copies the replacement text, changes the arguments to the actualArguments, and puts the result in place of the call. It does this without any form of checking. The results may not compile. Worse the often do something quite unexpected when they compile. As an example .As_is #define double(x) 2*x looks simple and OK. As an inline template function .As_is inline template double(T x) {return 2*x;} it works exactly as you expect. As a macro the following works .As_is double(3) the preprocessor replaces it by .As_is 2*3 and when run you get "6" as the answer. Now try .As_is double("boo") which attempts to compile .As_is 2*"boo" which fails to compile. Now suppose that you have .As_is double(1+1) which generates the code .As_is 2*1+1 which has value 3, rather than 4. As a result, wise macro programmers learn to write .As_is #define double(x) 2*(x) But.... macros still generate surprising (dangerous) results. .As_is #define max(x,y) ((x)<(y)?(x):(y)) which works well even with .As_is max(1+1, 2+2) which becomes .As_is ((1+1)<(2+2)?(1+1):(2+2)) and produces 4, as expected. But if we have .As_is int i=1; what does .As_is max(i++,i++) do? Answer, it becomes, .As_is ((i++)<(i++)?(i++):(i++)) and, this changes the value of i 3 times to become 4, and I'm not sure what it returns. And this is just the beginning with the confusions you can experience by using macros. They are not part of CSCI202. You can find them in an appendix of the text..... if you need them to work on old code. . Templates vs Macros -- just say no to macros These days use a template! . How are overloading and templates related . what are some of the similarities and difference between overloading and templates? Overloading::="One name, different data". First, writing a template function creates a lot of new functions that all overload each other -- they all have the same name and different types of data. Next a templated function may overload previous one. C++ uses a variation of the algorithm for resolving overloading to find the template that matches the given function call. . Can you overload a template Templates are always overloaded..... an you can (in theory) have a mixture of templates and plain functions with the same name and different data. But I think the compiler may get confused. Worse so might you, . When are templates useful You need to understand them because the C++ Library of functions and classes use templates a lot. So you use/call them many times in any program -- and probably don't even notice it. You write a new ones less often. Mainly in quizzes and finals:-) However when you realizes that you have an idea for a function that could be used with all types of data and would have the same code you might as well write a template function. (DRY): Don't repeat yourself! If you ever find you have written the same function with different data, then you should have written it once, using a template instead. Template classes chiefly appear as .Key data structures -- collections of items all of the same type. For example `vector`. Or a safe array. Again the standard C++ library the "STL" has a dozen of these ready to use.... more in classes 18 and 19. You can also create new ones ... but I'd suggest taking CSCI330 before you do this. . What is the difference between class templates and class template specializations A specialization happens when you substitute the actual parameters into the class template. It generates a special class that fits that particular given data. . Templates and Polymorphism --- are they complementary Yes. They come from two different developments in computer languages. One is handled by the compiler. The other at run time. One relies on a class hierarchy, the other does not. One needs a pointer and the other does not. . If so can you give an example on the board Probably not. . In what kinds of situations would you combine templates and polymorphism I think that this is how the iostream family of classes work. But in practice I can't think of an example of combining them. . Memory used by templates -- can it be ignored Since templates don't usually consume more memory than separate overloaded functions, is the fear of a template consuming more memory still something to look out for? No. Use them without fear of wasting memory. You'd end up using the same amount of machine code by coding each special version of the function or class by hand. . Stacks -- Last In First Out -- LIFO The book uses a stack, which it describes as a data structure where the last items input would be the first items retrieved, can you give an example of a stack being used? Demo in class. Lab later will show a classic use of a stack to evaluate expressions. . Examples of templated classes .See http://www/dick/examples/Array.cc .See http://www/dick/examples/arith_float_collection.h .See http://www/dick/examples/tstack.cc .See http://www/dick/examples/vector.cc .See http://www/dick/examples/vector.h .See http://www/dick/examples/gin_stack.h .See http://www/dick/examples/gtin_stack.cpp . Exercises Depends on the questions! Write a template function that returns the maximum of two things of the same type. Write a template function that returns the minimum of two things of the same type. Write a template function that swaps the values of two variables. Answer: .See ./10templates.cpp .Close CSci202 Computer Science II, Session 10, Template Functions . Next -- Streams .See http://www/dick/cs202/11.html . Next Project -- next week