0% found this document useful (0 votes)
4 views

S08.Template (3)

The document discusses C++ programming techniques focusing on templates, which allow the creation of functions and classes that can operate with any data type. It explains the concepts of function and class templates, their definitions, instantiation, specialization, and the use of multiple template parameters. Additionally, it covers practical examples, including function template overloading, class template specialization, and exercises for further understanding.

Uploaded by

thanh24101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

S08.Template (3)

The document discusses C++ programming techniques focusing on templates, which allow the creation of functions and classes that can operate with any data type. It explains the concepts of function and class templates, their definitions, instantiation, specialization, and the use of multiple template parameters. Additionally, it covers practical examples, including function template overloading, class template specialization, and exercises for further understanding.

Uploaded by

thanh24101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

C/C++ Programming Techniques

C++

Thanh-Hai Tran

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Template

 Concept
 Function template
 Class template

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Introduction

 Implementing multiple versions of similar


functions and classes, which are needed for various
types.
 Templates allow to construct both functions and
classes based on types that have not yet been stated.
 C++ allows to define templates – parameterized
families of related functions or classes
 A function template: define a group of statements for a
function using a parameter instead of a concrete type
 A class template: specifies a class definition using
parameter instead of a concrete type

2020 3
Introduction

 Templates are powerful programming tools.


 A template needs only be coded once. Individual functions
or classes are automatically generated when needed.
 A template offers a uniform solution for similar problems
allowing type-independent code to be tested early in the
development phase.
 Errors caused by multiple encoding are avoided.

2020 4
Template

2020 5
Template

 Concept
 Function template
 Class template

Electronics and Computer Engineering


School of Electronics and Telecommunications
Hanoi University of Science and Technology
1 Dai Co Viet - Hanoi - Vietnam
Defining a function template

 Declare prefixed: template <class [name of class]>


 Declare and define function with type as name of
class
template<class T>
int compare(T x, T y){
if(x == y) return 1;
else return 0;
}
 A template function is instantiated when it is first
called.
 The compiler determines the parameter type of T by
the function argument
 Ex: int a = compare(5, 6); // T is determined as
int type
2020 7
Other examples
template <class T> template <typename T>
void swap2(T& a, T& b){
T c = a; a = b; b = c;
}
 T is considered as type of a, b, c
 T is determined at the calling time
 T is parameter of template while a, b is parameter of
function
 Many template class could be used for a function
template <class Containter, class Object>
void push(Containter& s, Object o){
cout << "Push o into the containers s" << endl;
}
2020 8
Calling function 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

template <class T> T mmax(T a, T b) {


if (a > b) return a;
else return b;
}
template <class T> T mmax(T a, T b, T c){
T d = mmax(a, b);
if (d > c) return d;
else return c;
}
template <class T> T mmax(T* arr, int n){
T m = arr[0];
for(int i = 1; i < n; i++)
if (m < arr[i]) m = arr[i];
return m;
2020
} 10
Overloading function call
 max<int>(10, 20);
max('c', 'f');
max<double>(1.5, 2.1, 3.14);
max("1un34k", 6);
 What happen when ?
 mmax(n, c) with n is an integer number and c is a character
?
 The compiler will issue an error

2020 11
Specialization

string st1 = "DHBK";


string st2 = "CSDL";
cout << "max(st1, st2) = " << mmax(st1, st2) <<e
ndl;
max(st1, st2) = CSDL

The comparison between a and b is realized on values of


pointers (addresses)

template<> string mmax(string s1, string s2){


return s1.compare(s2) == 1 ? s1:s2;
}

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

 Return type of the function


template <class Worker, class Product>
Product makeProd(Worker& w) {
w.work();
return w.getResult();
}

 Type of local parameters


template <class List, class Iterator>
void forEach(const List& l) {
Iterator i = l.first();
for (; i!=l.last(); i = i.next())
doSmth(i.get());
}
2020 14
Parameter of template is not only type but …

 It could be value, then used as const


Template <class Object, int N>
Object* makeArray(){
return new Object[N];
}
string* p1 = makeArray<string, 5>();
Student* p2 = makeArray<Student, 10>();
 Both type and value as parameterized
Template <class T, T min, T max>
T range(T t) {
return t<min ? min : (t>max ? max : t);
}
y = range<double, -1.5, 2.> (x);
b = range<int, 10, 20> (a);
2020 15
Notes

 Function templates is compiled only when the type


information is available
 if function template is defined in a library, both the
prototype and its implementation are in .h file
 We can implement the template function separately in
another file and then include in the .h file
 When using parameters have a specific type, the compiler
generates the corresponding function
int a = 10, b = 20;
swap(a, b); //generate: void swap(int&, int&){}
swap<float>(x, y); // void swap(float&, float&){}

2020 16
Defining class template

 Similar to function template, class can be defined as


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; }

template<class Object> template<class Object>


Array<Object>::Array(int N) { Object& Array<Object>::
this->N = N; operator[](int i)
p = new Object[N]; } { return p[i]; }

2020 18
Multiple template parameters

template <class T, int n>


class Stack
{
private:
T arr[n]; // Array
int tip; // Tip of stack
int max; // Maximum number of elements
public:
Stack(){ max = n; tip = 0; };
bool empty(){ return (tip == 0); }
bool push( const T& x);
bool pop(T& x);
};

2020 19
More template parameters

 Restrictions
 Template parameters can not be modified
 And they can not be floating-point type

template<class Object, int N> template<class Object, double N


Object* makeArray(){ >
N++; // ERROR Object* makeArray(){
return new Object[N]; return new Object[N];
} }

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

typedef Array<string> StrArray;


StrArray s(2);
s[0] = string("abcd");
s[1] = string("12345");
 Combination of function templates and class templates
 template<class Object>
void printArray(Array<Object> &a) {
for (int i=0; i<a.length(); i++)
cout << a[i];
}

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

template<class Object = int, int N = 100>


class Pool {
...
};

Pool p1; //  Pool<int, 100> p1;


Pool<string> p2; //  Pool<string, 100> p2
Pool<double, 20> p3;
 Note:
 Only class template has default argument
 Not function template

2020 23
Relevant class templates
 template<class T> class Iterator;

template<class T> class List {


...
Iterator<T> begin() { ... }
Iterator<T> end() { ... }
};

template<T> class Iterator {


...
T& getData() { ... }
Iterator<T> next() { ... }
};

List<float> l;
...
Iterator<float> i;
for (i = l.begin(); i != l.end(); i = i.next())
cout << i.getData() << endl;
2020 24
Friend function

 Friend function of a class


 template<class T>
class Array {
...
friend void sort(Array<T>& a);
friend class Serializer<T>;
};

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

You might also like