Generic Programming - Templates

Templates

Outline

Class template

Function template

Template metaprogramming

Generic Programming - Templates

Templates

Allow generic programming

To write code that can work with all kind of objects

Template programmer's obligation: specify the requiments of the classes that define these objects

Template user's obligation: supplying those operators and methods that the template programmer requires

Generic Programming - Templates

Function Template

Allows writing function families

template<typename T>
const T max(const T& x, const T& y){
	return x < y ? y : x;
}
template<class T>
const T max(const T& x, const T& y){
	return x < y ? y : x;
}

What are the requirements regarding the type T?

Generic Programming - Templates

Function Template

template<class T>
const T max(const T& x, const T& y){
	return x < y ? y : x;
}

Requirements regarding the type T:

less operator (<)

copy constructor

Generic Programming - Templates

Function Template

template<class T>
const T max(const T& x, const T& y){
	return x < y ? y : x;
}

Usage:

cout << max(2, 3) << endl; //max: T -> int
string a = "alma";
string b = "korte";
cout << max(a, b) << endl; //max: T -> string
Person p1("John", "Kennedy"), p2("Abraham", "Lincoln");
cout << max(p1, p2) << endl; //max: T -> Person
			
Generic Programming - Templates

Function Template

template<class T>
void swap(T &x, T &y){
	const &T tmp = x;
	x = y;
	y = tmp;
}
			

Requirements regarding the type T:

Copy constructor

Assignment operator

Generic Programming - Templates

Function Template

Allow writing function families

polymorphism: compile time

How the compiler processes templates?

cout << max(2, 3) << endl; //max: T -> int
cout << max(2.5, 3.5) << endl; //max: T -> double
			

How many max functions

Warning: code bloat!

Generic Programming - Templates

Class Template

Allow writing class families

template<typename T>
class Array{
	T* elements;
	int size;
public:
	Array(const int size);
};
			
Generic Programming - Templates

Class Template

Template class's method definition

template<typename T>
class Array{
	T* elements;
	int size;
public:
	Array(const int size);
};
template<typename T>
Array<T>::Array(const int size):size(size), elements(new T[size]){
	
}
			
Generic Programming - Templates

Template

Generic Programming - Templates

Template

Generic Programming - Templates

Template

Generic Programming - Templates

Template

Generic Programming - Templates

Template

Generic Programming - Templates

Template