Discussion topics
Week of Feb 5th
Generic Programming with Templates
This is intended to re-familiarize you with using and creating templates in c++
What is Generic Programming?
-->types become parameters for functions.
-->functions depend only on required properites of elements they
operate on and disregard other (possibly differing) properties.
Example:
sort(v) can hide:
1)differing algorithms it can implement
2)differeng containers it can operate on
3)differing elements in the containers
Example:
c++ class string:
really a synonym for "basic_string"
-where basic_string is a templatized string'
-string has been given typedef basic_string
-typedef can shorten long names from templates
or hide details of how a type is defined
Defining a Template Class "List":
template class List {
struct Link {
Link* prev;
Link* next;
T val;
Link(Link* p, Link* n, const T& v) :prev(p), next(n), val(v) {}
};
Defining a Template Function "sort":
template void sort(vector&); // definition
template void sort(vector& v) {
const size_t n = v.size();
for (int gap=n/2; 0& vi;
vector& vs;
sort(vi);
sort(vs);
Using multiple arguments to temlate functions:
template T lookup (Buffer,const char* p);
Class Record{
.
.
}
int f(Buffer& buf, const char*p)
Function Template Overloading:
template T sqrt(T);
template complex sqrt(complex)
double(sqrt(double);
void f(complex z){
sqrt(2) //sqrt(int)
sqrt(2.0) //sqrt(double)
sqrt(z); //sqrt>(complex)
}