S08.Template (3)
S08.Template (3)
C++
Thanh-Hai Tran
Concept
Function template
Class template
2020 3
Introduction
2020 4
Template
2020 5
Template
Concept
Function template
Class template
Explicit call
max<int>(a, b);
max<double>(x, y);
swap<String&>(s1, s2);
swap<Worker*&>(p1, p2);
push<List&, Student>(l, st);
Implicit call
int a, b;
double x, y;
max(a, b); // max<int>(a, b);
max(x, y); // max<double>(x, y);
max(a, x); // lỗi
2020 9
Function template overloading
2020 11
Specialization
2020 12
Redefine operators <, > in template class
class vector{
int x, y;
public:
vector(int x_ = 0, int y_ = 0):x(x_),y(y_){}
void display()const{cout << x << " "<< y <<e
ndl;}
friend int operator> (vector a, vector b);
};
int operator> (vector a, vector b)
{
return (a.x*a.x + a.y*a.y) > (b.x*b.x+b.y*b.
y);
}
vector va(2,3), vb(3,4);
mmax(va, vb).display();
2020 13
Not only template for parameters but also
2020 16
Defining class template
template<class Object>
class Array {
private:
int N;
Object* p;
public:
void setAt(int i, Object o) {}
Object& operator[](int i) {}
};
2020 17
Function member outside class template
template<class Object> template<class Object>
class Array { Array<Object>::~Array()
private: { delete[] p; }
int N;
Object* p; template<class Object>
public: void Array<Object>::
Array(int N); setAt(int i, Object o)
~Array(); { p[i] = o; }
void setAt(int i, Object o);
int length() const; template<class Object>
Object& operator[](int i); int Array<Object>::length() const
}; { return N; }
2020 18
Multiple template parameters
2020 19
More template parameters
Restrictions
Template parameters can not be modified
And they can not be floating-point type
int n = 5;
string* p1 = makeArray<string, n>(); // ERROR
because n is a constant
2020
Using class template
Example:
Array<double> a(10);
for (int i=0; i<10; i++)
a.setAt(i, i*2);
printArray(a);
printArray(s);
2020 21
Class template specialization
template<class Key, class Data> class Map {
...
Data find(Key k);
};
// Fully specialization
template<> class Map<int, int> {
...
int find(int k);
};
// Partly specialization
template<class Data> class Map<int, Data> {
...
Data find(int k);
};
2020 22
Default arguments
2020 23
Relevant class templates
template<class T> class Iterator;
List<float> l;
...
Iterator<float> i;
for (i = l.begin(); i != l.end(); i = i.next())
cout << i.getData() << endl;
2020 24
Friend function
2020 25
Exercises
Function templates
Write a function allowing to set values (taken from keyboard)
for elements of arrays of any types
Write a function to sort an array using template:
template<class T> void sortCpp(T* a, int
n);
Class templates
Write a class Stack containing any kind of data
Write a class Vector to work with both float and double data
2020 26