Date post: | 26-Dec-2015 |
Category: |
Documents |
Upload: | spencer-hodges |
View: | 216 times |
Download: | 0 times |
1
159.234159.234 LECTURE 17LECTURE 17
More on TemplatesMore on Templates
2020
An abstract recipe for producing concrete code.
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.
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
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.
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;
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:
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
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
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
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;}
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
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.
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[]
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);
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
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;
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.
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>* >
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.
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); } }
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]; }
}
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()
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
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
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:
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
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)