Lec10-templates.pdf - AST21105 Object-Oriented Programming and Design Topic 10 Templates Lecture notes are based on textbook and various resources over

Lec10-templates.pdf - AST21105 Object-Oriented Programming...

This preview shows page 1 - 10 out of 32 pages.

AST21105 Object-Oriented Programming and Design Topic 10 Templates Lecture notes are based on textbook and various resources over the Internet
Image of page 1
Generic Programming 2
Image of page 2
Generic Programming o Such software entities are known as: n Parametric polymorphism in ML, Scala, Haskell and Julia; n Parameterized types in the influential book Design Patterns written by Gang of Four in 1994; n Generics in Ada, C#, Delphi, Eiffel, F#, Java, Rust, Swift, TypeScript, Visual Basic .NET; n Templates in C++ and D. 3
Image of page 3
Templates in C++ o In C++, templates are the mechanism to support generic programming. o There are two kinds of templates that can be defined in C++: n Function templates n Class templates. o They are particularly effective mechanisms for generic programming because they make the generalization possible without sacrificing efficiency . n Runtime execution is not getting slower, at the cost of longer compilation. 4
Image of page 4
5 Function Template o We often find a set of functions that look very much similar, for example: int max( int a, int b) { if (a > b) return a; else return b; } string max( const string& a, const string& b) { if (a > b) return a; else return b; }
Image of page 5
6 Function Template o In C++, we can make a single function definition using a feature known as function template . template <typename T> T max( const T& a, const T& b) { if (a > b) return a; else return b; } Note: - The template above is NOT a function and you CANNOT CALL IT. - Instead, it is a generator that generates a number of functions.
Image of page 6
7 Function Template o The keyword typename may be replaced by keyword class ; the following template definition is equivalent to the one on the last page: // No difference for writing // <typename T> or <class T> template <class T> T max( const T& a, const T& b) { if (a > b) return a; else return b; }
Image of page 7
8 Function Template o The compiler creates functions using function templates. n In this case, the compiler creates two different max() functions using the function template above. o This is called template instantiation . n Analogy: Just as instantiation of a class results in an object, instantiation of a function template results in a function. int i = 2, j = 3; // create a max function with T = int cout << max(i,j); string a("Hello"), b("World"); // create a max function with T = string cout << max(a, b);
Image of page 8
9 Function Template o The parameter T in the template definition is called a template parameter .
Image of page 9
Image of page 10

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture