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

159.234 LECTURE 17

  • Upload
    varian

  • View
    31

  • Download
    3

Embed Size (px)

DESCRIPTION

159.234 LECTURE 17. 20. More on Templates. An abstract recipe for producing concrete code. Templates. 19. Some Terms. Function Template. A function template is a template used to generate functions. e.g. template T Max (T x, T y) { if (x > y) return x; else return y; - PowerPoint PPT Presentation

Citation preview

Page 1: 159.234 LECTURE 17

1

159.234159.234 LECTURE 17LECTURE 17

More on TemplatesMore on Templates

2020

An abstract recipe for producing concrete code.

Page 2: 159.234 LECTURE 17

2

TemplatesTemplatesSome TermsSome Terms

FunctionFunction Template Template

1919

A function template is a template used to generate functions.

TemplateTemplate Function Function

A template function is a function that is produced by a template.

i = Max(j,k);

template <class T>T Max(T x, T y) { if (x > y) return x; else return y;}

e.g.

e.g.This function call tells the compiler to generate the actual template function.

Page 3: 159.234 LECTURE 17

3

TemplatesTemplatesSome TermsSome Terms

ClassClass Template Template

1919

A class template is a template that is used to generate classes.

TemplateTemplate Class Class

A template class is a class that is produced by a template.

template <class T>class Vector{ //class interface};

e.g.

e.g.Vector<int> m(100);Vector<Date> d(200);

Actual template class

Page 4: 159.234 LECTURE 17

4

TemplatesTemplatesFriendsFriends

1919

template <class T>class matrix{ public: friend void foo_bar(); //universal friend vect<T> product(vect<T> 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.

Page 5: 159.234 LECTURE 17

5

TemplatesTemplatesStatic MembersStatic Members

1919

template <class T>class Vect{ public: static int count; //…};

Static members are not universal but are specific to each instantiation.

Static variables Vect<int>::count and Vect<double>::count are distinct.

Vect<int> a;Vect<double> b;

Page 6: 159.234 LECTURE 17

6

TemplatesTemplatesDefault Template ArgumentsDefault Template Arguments

1919

template <class T=int>class Vect{ public: //…};

You can assign a default type to your class template

Vect< > a;Vect<double> b;

Default type

Instantiation:

Page 7: 159.234 LECTURE 17

7

TemplatesTemplatesMember TemplatesMember Templates

1919

template <class T1>class Vect{ public: template<class T2> 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<int>::Complex<float> a;

class member template

New feature of ANSI standard - yet to be implemented on most C++ compilers

Page 8: 159.234 LECTURE 17

8

1. Not using template<class T> 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<class T, class S>

If a template is invoked with a user defined class typeand that template uses operators (==, +, <=, etc.) with objects of that class type, then those operators must be overloaded.

Common ErrorsCommon Errors with Templates with Templates

Page 9: 159.234 LECTURE 17

9

Macros present the possibility of having side effects because they do not usually have type checking.

#define SQ(A) ((A)*(A))

template<class T> T square (T x){

return x*x;}

Templates vs. MacrosTemplates vs. Macros

Page 10: 159.234 LECTURE 17

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. MacrosTemplates vs. Macros

#define SQ(A) ((A)*(A))

template<class T> T square (T x){

return x*x;}

Page 11: 159.234 LECTURE 17

11

TemplatesTemplatesClass Template ExampleClass Template Example

Vector Class TemplateVector Class Template

1919

Vector()Vector()~Vector()operator=()operator[]Size()

See VectorT.cpp

copy()

public:

protected:

Vector <Vector <shortshort>>Vector()Vector()~Vector()operator=()operator[]Size()

copy()

Instantiated from the Class template

sizedata

xx

sizedata

yy

xx & yy are both instantiated from the Template classVector<short>

CannotCannot be invoked byany of the class instances

Page 12: 159.234 LECTURE 17

12

TemplatesTemplatesSubClass Template ExampleSubClass Template Example

Vector Class TemplateVector Class Template

1919

Vector()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, aswell as perform some modifications.

Page 13: 159.234 LECTURE 17

13

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Array Class TemplateArray Class Template

1919

template <class T>class Array : public Vector<T>public Vector<T>{ public:

Array(int i, int j) : Vector<T>(j-i+1), i0i0(i) {} Array(const Array<T>& v) : i0i0(v.i0), Vector<T>(v) {} T& operator[](int i) const { return Vector<T>::operator[](i-i0);Vector<T>::operator[](i-i0);}

int firstsubscript() const {return i0i0;} int lastsubscript() const {return i0i0 + Vector<T>::size - 1;}

protected: int i0int 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[]

Page 14: 159.234 LECTURE 17

14

TemplatesTemplatesClass Template ExampleClass Template Example

What if we want to allow for an ordinary array to What if we want to allow for an ordinary array to be replicated as a vector?be replicated as a vector?

1919

See Replicating an ordinary array as a vector.cpp

int a[] = {11, 22, 33, 44, 55};

Vector<int> v(a);

Page 15: 159.234 LECTURE 17

15

// multidimensional_arrays.cpp // compile with: /EHsc // arguments: 3

#include <limits> // Includes DBL_MAX #include <iostream>

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

Page 16: 159.234 LECTURE 17

16

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Our own class templates can accept built-in Our own class templates can accept built-in classes as template parameter:classes as template parameter:

1919

See Matrix.cpp

Vector<string> a;

Since template classes work like ordinary classes, Since template classes work like ordinary classes, we can also pass them to template parameters:we can also pass them to template parameters:

Stack<Vector<int>> b; Array<Stack<Vector<int>> > c;

Page 17: 159.234 LECTURE 17

17

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Matrix – essentially a 2D vectorMatrix – essentially a 2D vector

1919

See Matrix.cpp

It can be represented as a 2-element Vector, each It can be represented as a 2-element Vector, each of whose elements is a 3-element Vector:of whose elements is a 3-element Vector:

abc

def

a 2-by-3 Matrix is a table with 2-rows &3-columns

abc def This representation would allow us to useour Vector class template to define a newMatrix class template.

Page 18: 159.234 LECTURE 17

18

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

To facilitate dynamic allocation of memory, we To facilitate dynamic allocation of memory, we define a Matrix as a Vector of Pointers to Vectorsdefine a Matrix as a Vector of Pointers to Vectors

1919

See Matrix.cpp

When the Matrix class template is instantiated, the When the Matrix class template is instantiated, the Instances of the resulting class will contain Instances of the resulting class will contain vectors of pointers to vectors.vectors of pointers to vectors.

Vector< Vector<T>* >

Page 19: 159.234 LECTURE 17

19

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Matrix Class TemplateMatrix Class Template

1919

See Matrix.cpp

template<class T>class Matrix{

public: Matrix(unsigned r=1, unsigned c=1) : row(r) {//… } ~Matrix(){ //… }

Vector<T>& operator[](unsigned i) const {//… } unsigned rows() {return row.size(); } unsigned columns() {return row[0]->size(); }

//(*row).size()

protected: Vector<Vector<T>*> row;

};

Vector of pointers to Vectors

Matrix class template connects to the Vector class template via composition.

Page 20: 159.234 LECTURE 17

20

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Matrix Class Template : Constructor Matrix Class Template : Constructor

1919

See Matrix.cpp

Matrix(unsigned r=1, unsigned c=1) : row(r) { for(int i=0; i < r; i++) { row[i] = new Vector<T>(c); } }

Page 21: 159.234 LECTURE 17

21

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Matrix Class Template : Destructor Matrix Class Template : Destructor

1919

See Matrix.cpp

~Matrix(){ for(int i=0; i < row.Size(); i++) {

delete row[i]; }

}

Page 22: 159.234 LECTURE 17

22

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Matrix Class Template : Subscripting Operator Matrix Class Template : Subscripting Operator

1919

See Matrix.cpp

Vector<T>& operator[](unsigned i) const { return *row[i];

}

unsigned rows() {return row.Size(); } unsigned columns() {return row[0]->Size(); } //(*row).size()

Page 23: 159.234 LECTURE 17

23

Nested TemplatesNested TemplatesPassing Template Classes to Template ParametersPassing Template Classes to Template Parameters

Creating an Instance of the Matrix Class Template :Creating an Instance of the Matrix Class Template :

1919

See Matrix.cpp

Matrix<float> a(2, 3);

data

size=3

0.00.10.2

012

data

size=3

1.01.11.2

012

Vector<float> Vector<float>

row

size=2

01

Matrix<float>

aMatrix()

~Matrix()

operator[]

rows()

columns()

Matrix<float> Vector of pointers to Vectors

Page 24: 159.234 LECTURE 17

24

Nested TemplatesNested TemplatesExtracting an element of the Matrix Template Class Extracting an element of the Matrix Template Class aa::

1919

See Matrix.cpp

a[1][2]

data

size=3

0.00.10.2

012

data

size=3

1.01.11.2

012

Vector<float> Vector<float>

row

size=2

01

Matrix<float>

aMatrix()

~Matrix()

operator[]

rows()

columns()

Matrix<float>

Matrix operator[1]Vector operator[1]Vector operator[2]

invokes the following operators:Matrix operator[1]Vector operator[1]data[i] = 0x4d3f58Vector operator[2]data[i] = 1.2m[1][2] = 1.2

Page 25: 159.234 LECTURE 17

25

Nested TemplatesNested TemplatesExtracting an element of the Matrix Template Class Extracting an element of the Matrix Template Class aa::

1919

See Matrix.cpp, Matrix_stl.cpp

a[0][2]

data

size=3

0.00.10.2

012

data

size=3

1.01.11.2

012

Vector<float> Vector<float>

row

size=2

01

Matrix<float>

aMatrix()

~Matrix()

operator[]

rows()

columns()

Matrix<float>

Matrix operator[0]Vector operator[0]Vector operator[2]

invokes the following operators:

Page 26: 159.234 LECTURE 17

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.

SummarySummary

Page 27: 159.234 LECTURE 17

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)Standard Template Library (STL)