Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 159.234LECTURE 17 159.234 LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.

Similar presentations


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

1 1 159.234LECTURE 17 159.234 LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.

2 2Templates Some Terms Function Template 19 A function template is a template used to generate functions. Template Function A template function is a function that is produced by a template. i = Max(j,k); template T Max(T x, T y) { if (x > y) return x; else return y; } e.g. This function call tells the compiler to generate the actual template function.

3 3Templates Some Terms Class Template 19 A class template is a template that is used to generate classes. Template Class A template class is a class that is produced by a template. template class Vector{ //class interface }; e.g. Vector m(100); Vector d(200); Actual template class

4 4TemplatesFriends 19 template class matrix{ public: friend void foo_bar(); //universal friend vect product(vect v); //instantiated }; A friend function that does not use a template specification is universally a friend of all instantiations of the template class. A friend function that incorporates template arguments is specifically a friend of its instantiated class.

5 5Templates Static Members 19 template class Vect{ public: static int count; //… }; Static members are not universal but are specific to each instantiation. Static variables Vect ::count and Vect ::count are distinct. Vect a; Vect b;

6 6Templates Default Template Arguments 19 template class Vect{ public: //… }; You can assign a default type to your class template Vect a; Vect b; Default type Instantiation:

7 7Templates Member Templates 19 template class Vect{ public: template class Complex{ //… //can use T1 and T2 in Complex }; //can only use T1 in Vect }; Members may themselves be templates inside the template class. Vect ::Complex a; class member template New feature of ANSI standard - yet to be implemented on most C++ compilers

8 8 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 (==, +, <=, etc.) with objects of that class type, then those operators must be overloaded. Common Errors with Templates

9 9 Macros present the possibility of having side effects because they do not usually have type checking. #define SQ(A) ((A)*(A)) template T square (T x){ return x*x; } Templates vs. Macros

10 10 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 #define SQ(A) ((A)*(A)) template T square (T x){ return x*x; }

11 11Templates Class Template Example Vector Class Template 19 Vector() ~Vector() operator=() operator[] Size() See VectorT.cpp copy() public: protected: Vector Vector Vector() ~Vector() operator=() operator[] Size() copy() Instantiated from the Class template size data x size data y xy x & y are both instantiated from the Template class Vector Cannot Cannot be invoked by any of the class instances

12 12Templates SubClass Template Example Vector Class Template 19 Vector() ~Vector() operator=() operator[] Size() copy() public: protected: e.g. Instead of the range [0, 100], we want to have [1, 100], or even [-100, 100]. What if we want to allow the user to designate the range of indexes for the Vector class? We can derive a new class that could Inherit all the functionalities of Vector, as well as perform some modifications.

13 13 Nested Templates Passing Template Classes to Template Parameters Array Class Template 19 template public Vector class Array : public Vector { public: i0 Array(int i, int j) : Vector (j-i+1), i0(i) {} i0 Array(const Array & v) : i0(v.i0), Vector (v) {} Vector ::operator[](i-i0); T& operator[](int i) const { return Vector ::operator[](i-i0);} i0 int firstsubscript() const {return i0;} i0 int lastsubscript() const {return i0 + Vector ::size - 1;} protected: int i0 int i0; //index 0 (or first index number) }; Array class template connects to the Vector class template via inheritance. See Subclass Template for Vectors.cpp Explicitly calls the Vector operator[]

14 14Templates Class Template Example What if we want to allow for an ordinary array to be replicated as a vector? 19 See Replicating an ordinary array as a vector.cpp int a[] = {11, 22, 33, 44, 55}; Vector v(a);

15 15 // multidimensional_arrays.cpp // compile with: /EHsc // arguments: 3 #include // Includes DBL_MAX #include const int cMkts = 4, cFacts = 2; // Declare a float that represents the transportation costs double TransportCosts[][cMkts] = { { 32.19, 47.29, 31.99, 19.11 }, { 11.29, 22.49, 33.47, 17.29 }, { 41.97, 22.09, 9.76, 22.55 } }; // Calculate size of unspecified dimension const int cFactories = sizeof TransportCosts / sizeof( double[cMkts] ); http://msdn.microsoft.com/en-us/library/7wkxxx2e.aspx

16 16 Nested Templates Passing Template Classes to Template Parameters Our own class templates can accept built-in classes as template parameter: 19 See Matrix.cpp Vector a; Since template classes work like ordinary classes, we can also pass them to template parameters: Stack > b; Array > > c;

17 17 Nested Templates Passing Template Classes to Template Parameters Matrix – essentially a 2D vector 19 See Matrix.cpp It can be represented as a 2-element Vector, each of whose elements is a 3-element Vector: a 2-by-3 Matrix is a table with 2-rows & 3-columns This representation would allow us to use our Vector class template to define a new Matrix class template.

18 18 Nested Templates Passing Template Classes to Template Parameters To facilitate dynamic allocation of memory, we define a Matrix as a Vector of Pointers to Vectors 19 See Matrix.cpp When the Matrix class template is instantiated, the Instances of the resulting class will contain vectors of pointers to vectors. Vector * >

19 19 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template 19 See Matrix.cpp template class Matrix{ public: Matrix(unsigned r=1, unsigned c=1) : row(r) {//… } ~Matrix(){ //… } Vector & operator[](unsigned i) const {//… } unsigned rows() {return row.size(); } unsigned columns() {return row[0]->size(); } //(*row).size() protected: Vector *> row; }; Vector of pointers to Vectors Matrix class template connects to the Vector class template via composition.

20 20 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template : Constructor 19 See Matrix.cpp Matrix(unsigned r=1, unsigned c=1) : row(r) { for(int i=0; i < r; i++) { row[i] = new Vector (c); }

21 21 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template : Destructor 19 See Matrix.cpp ~Matrix(){ for(int i=0; i < row.Size(); i++) { delete row[i]; }

22 22 Nested Templates Passing Template Classes to Template Parameters Matrix Class Template : Subscripting Operator 19 See Matrix.cpp Vector & operator[](unsigned i) const { return *row[i]; } unsigned rows() {return row.Size(); } unsigned columns() {return row[0]->Size(); } //(*row).size()

23 23 Nested Templates Passing Template Classes to Template Parameters Creating an Instance of the Matrix Class Template : 19 See Matrix.cpp Matrix a(2, 3); data size=3 0.0 0.1 0.2 0 1 2 data size=3 1.0 1.1 1.2 0 1 2 Vector row size=2 0 1 Matrix a Matrix() ~Matrix() operator[] rows() columns() Matrix Vector of pointers to Vectors

24 24 Nested Templates Extracting an element of the Matrix Template Class a: 19 See Matrix.cpp a[1][2] data size=3 0.0 0.1 0.2 0 1 2 data size=3 1.0 1.1 1.2 0 1 2 Vector row size=2 0 1 Matrix a Matrix() ~Matrix() operator[] rows() columns() Matrix Matrix operator[1] Vector operator[1] Vector operator[2] invokes the following operators: Matrix operator[1] Vector operator[1] data[i] = 0x4d3f58 Vector operator[2] data[i] = 1.2 m[1][2] = 1.2

25 25 Nested Templates Extracting an element of the Matrix Template Class a: 19 See Matrix.cpp, Matrix_stl.cpp a[0][2] data size=3 0.0 0.1 0.2 0 1 2 data size=3 1.0 1.1 1.2 0 1 2 Vector row size=2 0 1 Matrix a Matrix() ~Matrix() operator[] rows() columns() Matrix Matrix operator[0] Vector operator[0] Vector operator[2] invokes the following operators:

26 26 C++ uses templates to provide generic programming. Templates are one of C++’s features that allow for software reuse. By allowing the user of the class template to provide the data type through the specification of the type parameter during instantiation, the same code can be utilized for different types.Summary

27 27 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)


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

Similar presentations


Ads by Google