Download presentation
Presentation is loading. Please wait.
Published byAugustine Eaton Modified over 8 years ago
1
Generic Programming in C++ Giuseppe Attardi Università di Pisa
2
Generic Parameters Function for squaring a number: Function for squaring a number: sqr(x) { return x * x; } C version: C version: int sqr(int x) { return x * x; } Multiple versions: Multiple versions: int sqrInt(int x) { return x * x; } C++ overloading: C++ overloading: int sqr(int x) { return x * x; } double sqr(double x) { return x * x; }
3
C++ Templates template template T sqr(T x) { return x * x; } Compiler automatically generates a version for each parameter type used by a program: Compiler automatically generates a version for each parameter type used by a program: int a = 3; double b = 3.14; int aa = sqr(a); double bb = sqr(b);
4
Notes: macros’ limits #define sqr(x) ((x) * (x)) int aa = sqr(a++); int aa = ((a++) * (a++)); int aaa = sqr(aa); #define fact(n) (n == 0) ? 1 : fact(n-1) * n #define SQR(T) T sqr(T x) {return x * x; } SQR(int);SQR(double);sqr(a);sqr(b);
5
Other types as well? class Complex { double real, imag; Complex operator *(Complex y) { return Complex( real * y.real – imag * y.imag, real * y.imag + imag * y.real); } } Complex c(1, 2); Complex cc = sqr(c);
6
Compile time checking template template void swap(T& a, T& b) { const T temp = a; a = b; b = temp; } int a = 5, b = 9; int& ar = a; int* ap = *a; ar++; *ap = (*ap)+1 ar++; *ap = (*ap)+1 swap(a, b);// OK double c = 9.0; swap(a, c);// error
7
C++ Standard Template Library Goal: represent algorithms in as general form as possible without compromising efficiency Goal: represent algorithms in as general form as possible without compromising efficiency Extensive use of templates Extensive use of templates Only uses static binding (an inlining) Only uses static binding (an inlining) Use of iterators for decoupling algorithms from containers Use of iterators for decoupling algorithms from containers Iterator: abstraction of pointers Iterator: abstraction of pointers
8
STL Organization Containers Containers vector, deque, list, set, map, … Algorithms Algorithms for_each, find, transform, sort Iterators Iterators forward_iterator, reverse_iterator, istream_iterator, … Function Objects Function Objects plus, equal, logical_and, project1 Allocators Allocators
9
Examples from C++ Annotations vector vector inner_product inner_product sort sort
10
Forward Iterator int main(int argc, char **argv) { vector args(argv, argv + argc); vector args(argv, argv + argc); vector ::iterator iter = args.begin(); vector ::iterator iter = args.begin(); for ( ; iter != args.end(); ++iter ) for ( ; iter != args.end(); ++iter ) cout << *iter << " "; cout << endl; cout << endl;
11
Reverse Iterator vector ::reverse_iterator iter = args.rbegin(); vector ::reverse_iterator iter = args.rbegin(); for (; iter != args.rend(); ++iter ) for (; iter != args.rend(); ++iter ) cout << *iter << " "; cout << endl; cout << endl;
12
Inner Product vector ia1 = {1, 2, 3, 4, 5, 6, 7}; vector ia2 = {7, 6, 5, 4, 3, 2, 1}; // dot product inner_product(ia1.begin(), ia1.end(), ia2.begin(), 0);
13
inner_product: definition T inner_product(InputIterator first1, InputIterator last1, InputIterator first2, InputIterator last1, InputIterator first2, T init, BinaryFunction op1, BinaryFunction op2); T init, BinaryFunction op1, BinaryFunction op2); Initializes result to init Initializes result to init For each iterator i1 in [first1, last1), and i2 = first2 + (i1 - first1)) updates result as follows: For each iterator i1 in [first1, last1), and i2 = first2 + (i1 - first1)) updates result as follows: result = op1(result, op2(*i1, *i2))
14
Inner Product (string concat) class Join { class Join { public: public: Join(string const &sep): sep(sep) {} Join(string const &sep): sep(sep) {} string operator()(string const& s1, string const& s2) { string operator()(string const& s1, string const& s2) { return s1 + sep + s2; } return s1 + sep + s2; } private: private: string sep; string sep; }; }; vector names1= {"Frank", "Karel", "Piet"}; vector names2 = {"Brokken", "Kubat", "Plomp"}; inner_product(names.begin(), names1.end(), names2.begin(), "\t“, Join("\n"), Join(" ")) ;
15
Parametrized Bubblesort template template struct greater { bool operator()(const T& a, const T& b) const { return a > b; }; template template struct less { bool operator()(const T& a, const T& b) const { bool operator()(const T& a, const T& b) const { return a < b; };
16
Note int x = 3, y = 5; bool b = greater ()(x, y);
17
Function object version template > void bubblesort(vector a, const C& comp) { for (unsigned i = 0; i < a.size(); ++i) for (unsigned i = 0; i < a.size(); ++i) for (unsigned j = i+1; j < a.size(); ++j) for (unsigned j = i+1; j < a.size(); ++j) if (comp(a[i], a[j])) swap(a[i], a[j]); };
18
Traditional Functional version template template void bubblesort(vector a, bool (*comp)(T&, T&)) { for (unsigned i = 0; i < size; ++i) for (unsigned i = 0; i < size; ++i) for (unsigned j = i+1; j < size; ++j) for (unsigned j = i+1; j < size; ++j) if (comp(a[i], a[j])) swap(a[i], a[j]); };
19
Bubblesort usage vector x = {1, 5, 3, 4, 2}; bubblesort(x, greater ()); bubblesort(x, less ()); // implicit type inference vector f; bubblesort(f);// uses less bubblesort(f);// uses less
20
(Partial) Template Specialization an alternate version of the class template code can be provided for certain template parameterstemplate<> void bubblesort >(…) { } partial specialization: when only some of the template parameters are supplied
21
Template Enumeration template template class Vector : public vector { public: Enumeration getEnumeration() { return (Enumeration(*this)); } class Enumeration { … } };
22
Enumeration (2) class Enumeration { private: private: vector const& v; vector const& v; unsigned idx; unsigned idx; public: public: Enumeration(vector const& vector) : Enumeration(vector const& vector) : v(vector), idx(0) { } v(vector), idx(0) { } T const& next() { // uses T T const& next() { // uses T if (idx == vp.size()) if (idx == vp.size()) throw NoSuchElementException(index); throw NoSuchElementException(index); return vp[idx++]; return vp[idx++]; } bool hasNext() { return idx < vp.size(); } bool hasNext() { return idx < vp.size(); }};
23
Enumeration (3) Vector vector; … Vector ::Enumeration en = vector.getEnumeration(); while (en.hasNext()) cout << en.next() << endl;
24
Issue: template instantiation // file sumVector.h template template T sumVector(T* array, unsigned n) { T sum(0); for (int i = 0; i < n; ++i) sum += array[i]; sum += array[i]; return sum; }
25
Instantiation (1) #include "sumVector.h" int x[] = {1, 2}; double y[] = {1.1, 2.2}; cout << sumVector(x, 2) << endl << sumVector(y, 2) << endl; If the same template function definition is included in different source files, separately compiled and linked, there will be only one instantiation, per type of template function If the same template function definition is included in different source files, separately compiled and linked, there will be only one instantiation, per type of template function
26
Instantiation (2) declare a template function, if it is known that the required instantiation is available in another source file: declare a template function, if it is known that the required instantiation is available in another source file: template template T sumVector(T* tp, unsigned n); int v[] = {1, 2}; sumVector(v, 2);
27
Instantiation (3) declare template functions in header files, keep the definition in a template source file: declare template functions in header files, keep the definition in a template source file: template template T sumVector(T* tp, unsigned n) { return *tp; return *tp;} static void* p1 = static_cast (sumVector);
28
Forcing Instantiations static void* p[] = { static_cast (sumVector), static_cast (sumVector), static_cast (sumVector) static_cast (sumVector)};
29
Explicit Instantiations template template T sumVector(T *tp, unsigned n) { return (*tp); } template int sumVector (int *, unsigned); template double sumVector (double *, unsigned); template unsigned sumVector (unsigned *, unsigned);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.