80 likes | 296 Views
Chapter 1 C++ Templates. Sections 1.6 and 1.7. Templates. Type-independent patterns that can work with multiple data types Generic programming Code reusable Function Templates These define logic behind the algorithms that work for multiple data types Class Templates
E N D
Chapter 1C++ Templates Sections 1.6 and 1.7
Templates • Type-independent patterns that can work with multiple data types • Generic programming • Code reusable • Function Templates • These define logic behind the algorithms that work for multiple data types • Class Templates • These define generic class patterns into which specific data types can be plugged in to produce new classes
Function Templates • Algorithms may use the same logic for different data types • Different definitions are written just to deal with different data types • Templates permit a common code, independent of the data type • Templates should be in header files, so that the compiler will know how to generate code when it sees the template used • Examples • Lec4/largest.h/cpp, uselargest.cpp Error with template in the .cpp file $ g++ uselargest.cpp largest.cpp /tmp/ccAg3qmY.o: In function `main': uselargest.cpp:(.text+0x133): undefined reference to `int tlargest<int>(int*, int)' uselargest.cpp:(.text+0x16c): undefined reference to `float tlargest<float>(float*, int)'
Class Templates • Identical code can be used for classes that have data of different types • Examples • Lec4/pair.h, usepair.cpp • Use friend function to access private members (example, for IO) • The approach used in the text is also ok • Note the use of a space between > and > in usepair.cpp • This makes the compiler realize that >> is not a single token 4
An Alternative to friend • Use a public ‘print’ function and an operator that calls it
STL Containers Container: stores other objects Common operations such as: push_back, back, front, [ ], etc Not all operations are defined for all containers Sequence: positions of elements are important Example: vector, list Associative containers: elements are accessed through keys Example: map, set, pair Example Lec4/vlm.cpp for example with vector, list, and map 6
STL Iterators Iterator: like a pointer to elements of a container Used to access elements of a container Popular operators * (dereference), ++, --, ==, != Examining all the elements of a container c.begin() returns an iterator to the first element of container c c.end returns a pointer to one past the end 7
Matrices • C++ library does not provide a matrixclass • Constructor • Creates rows number of zero-sized vectors • Resizes each vector to col elements • Two types of [ ] operators • One for LHS that returns by reference • Another for RHS that returns by constant reference • to[i] = from[i] • So we have two very identical functions • What makes their signatures different?