The C Template Friend and Standard Template Library
The C++ Template, Friend, and Standard Template Library Chien Chin Chen Department of Information Management National Taiwan University
The C++ Template (chapter 8. 5)
Class Templates (1/6) o Suppose your algorithm requires two kinds of lists: n o A list of real numbers and a list of integers. You have to define two list classes: n n Real. List and Int. List. Copy almost everything and change the class names and data type of items. class Real. List {. . . } Real. List: : Real. List() {. . . } class Int. List {. . . } Real. List. h Real. List. cpp Int. List. h Int. List: : Int. List() {. . . } Int. List. cpp 3
Class Templates (2/6) o o C++ class templates describes a class in terms of a data-type parameter. When declare instances of the class (i. e. , objects), the actual data type is passed to the class as an argument. n E. g. , New. List<int> New. List<double> class template int. List; double. List; data type as an argument YOU CAN AVOID MULTIPLE CLASS DEFINITIONS!! 4
Class Templates (3/6) Declaration template <typename T> The class definition is preceded by class New. Class template <typename T> { public: T is the data type that the calling New. Class(); program will specify. New. Class(T initial. Data); void set. Data(T new. Data); T get. Data(); In a calling program: New. Class<int> x; private: T the. Data; int substitutes T }; 5
Class Templates (4/6) Implementation template <typename T> New. Class<T>: : New. Class() { } template <typename T> New. Class<T>: : New. Class(T initial. Data) : the. Data(initial. Data) { } template <typename T> void New. Class<T>: : set. Data(T new. Data) { the. Data = new. Data; } template <typename T> T New. Class<T>: : get. Data() { return the. Data; } o o You precede each method with template <typename T>. And follow each occurrence of class name New. Class with <T>. 6
Class Templates (5/6) Using #include “New. Class. h” When declare instances of the class, int main() the actual data type is passed to { the class as an argument. New. Class<int> first; New. Class<double> second(4. 8); first. set. Data(5); } 7
Class Templates (6/6) Notes o When T is a user-defined data type. template <typename T> void New. Class<T>: : set. Data(T new. Data) { the. Data = new. Data; } assignment operator of T should be defined. (shallow/deep copy, see 8. 6 Overloadded operators) 8
Revised Pointer-based ADT List (1/4) o We revise the pointer-based list class as a class template. List // List. Node. T. h List. Node. . . size template <typename T> item head class List. Node { private: List. Node(): next(NULL) {} List. Node(const T & node. Item, List. Node *ptr) : item(node. Item), next(ptr) {} T item; List. Node<T> *next; friend class List<T>; }; 9
Revised Pointer-based ADT List (2/4) // List. T. h #include “List. Node. T. h” List. . . List. Node size template <typename T> item class List head { public: List(); List(const List<T> & a. List); . . . virtual void insert(int index, const T &new. Item) throw(List. Index. Out. Of. Range. Exception, List. Exception); . . . private: int size; List. Node<T> *head; . . . }; We generally have to include the #include “List. T. cpp” 10 implementation file at the end of the header file.
// List. T. cpp … template <typename T> void List<T>: : insert(int index, const T & new. Item) throw(List. Index. Out. Of. Range. Exception, List. Exception) { int new. Length = get. Length() + 1; if((index < 1) || index > new. Length)) throw List. Index. Out. Of. Range. Exception(“insert index out of range”); else { try { List. Node<T> *new. Ptr = new List. Node<T>; to access private size = new. Length; item of List. Node new. Ptr->item = new. Item; in List, List must special case be a friend of if(index == 1) List. Node. { new. Ptr->next = head; 11 head = new. Ptr; }
else { } } } general case List. Node<T> *prev = find(index-1); new. Ptr->next = prev->next; prev->next = new. Ptr; } catch(ball_alloc e) { throw List. Exception(“ cannot allocate memory”); } 12
Revised Pointer-based ADT List (3/4) o Program that uses the class template: #include “List. T. h” int main() { List<double> float. List; List<char> char. List; use one class definition for various types of lists. float. List. Insert(1, 1. 1); char. List. Insert(1, ’a’); . . . } 13
Revised Pointer-based ADT List (4/4) o Notes: n As usual, you place the class template declaration and its implementation in two separate files. o n Most compilers must see how the client (calling program) uses the class template before they can compile the template’s implementation file. o n List. T. h & List. T. cpp. To know what T is and substitute T with actual data type in the implementation file. Therefore, we usually include the implementation file at the end of the header file, and then include the header in the client program. 14
The C++ Friend (chapter 8. 3)
Friends (1/4) o Functions and classes can be friends of a class C. n n Friend functions are not members of the class C. Friend functions can access the private and protected members of the class C. 16
Friends (2/4) class sphere { public: … friend void read. Sphere. Data(Sphere& s); private: double the. Radius; }; outside functions access private data of a class via friend. void read. Sphere. Data(Sphere& s) { count << “Enter sphere radius: “; cin >> s. the. Radius; } 17
Friends (3/4) o While it (friend) violates the principle of information hiding, it is done in a controlled manner. n o Only certificated friends can have the access. Input and output functions are often defined as friend functions. n n When you know the context (environment) where you will use a class, you can decide exactly how the input and output will occur. And recompiling the class is not necessary each time you use a different technique for input and output. 18
Friends (4/4) o o Declaring a class B as a friend of a class C allows all of the methods of B to have access to the private and protected parts of C. A class List can be a friend of the class List. Node n List can access List. Node’s private and protected members. class List. Node { private: … List. Item. Type item; List. Node *next; friend class List; }; 19
The C++ Standard Template Library (chapter 4. 5)
The C++ Standard Template Library (1/2) o The C++ STL (Standard Template Library) contains class templates for some common ADTs, including the list class. n Many of the ADTs that are presented in this course have a corresponding class in the STL!! o o For example, the STL list class. Why do we spend so much time on developing ADTs in this text if they are already provided in the STL? n n n Provide a foundation for learning to develop other ADTs. You may find yourself working in a language that does not provide any predefined ADTs. You need to develop or enhance existing ones. 21
The C++ Standard Template Library (2/2) o The STL provides support for predefined ADTs through three basic items: n Containers: o n Iterators: o n Objects that hold other objects. Provide a way to cycle through the contents of a container. Algorithms: o That act on containers. 22
Containers o o Containers rely heavily on the C++ class template. STL containers actually use two data-type parameters. 1. 2. Data type for the items in the containers. Allocator, manage memory allocation for a container. o n Default allocator (an object of class allocator) is sufficient for most uses, and will be omitted in the following context. Example: list<int> my. List; #include <list> 23
Iterators (1/2) o A generalization of pointers. o To cycle through the items in a container. n o Very similar to the way you use a pointer. If you have an iterator called curr: n *curr; o n ++curr; o n Access the item in the container that curr references. Move the iterator to the next item in the container. --curr; 24
Iterators (2/2) o The container classes typically provide at least two methods that are useful for working with iterators. n iterator begin(); o n Initializes an iterator to reference the first item in the container. iterator end(); o o Return a value that indicates whether you have reached the end of the container. Very similar to the value NULL, but not NULL. n Example: for(curr = my. List. begin(); curr!= my. List. end(); curr++) ; 25
The STL class list o The STL class list is typically implemented as a circular doubly linked list. n o o With a dummy head node. The begin returns an iterator to the first item in the list. The end returns an iterator to the dummy head node in the list. The concept of circular doubly linked list with a dummy head 26
The STL class list o A partial list of the definition of the STL list: template <typename T> class std: : list { public: list(); . . . iterator insert(iterator i, const T& val = T()); . . . iterator begin(); iterator end(); • insert an item val into the list. . . } immediately before the element specified by the iterator i. • return an iterator to the newly inserted item. 27
The STL class list o Example of how to use the STL class list. #include <list> #include <iostream> #include <string> using namespace std; int main() { list<string> grocery. List; list<string>: : iterator i = grocery. List. begin(); i = grocery. List. insert(i, ”apples”); i = grocery. List. insert(i, ”bread”); i = grocery. List. begin(); while(i != grocery. List. end()) { cout << *i << endl; i++; } } output: bread apples 28
Summary o o A class template enables you to defer choosing some data-types within a class until you use it. The Standard Template Library (STL) contains class templates for some common ADTs. A container is an object that holds other objects. An iterator cycles through the contents of a container. 29
- Slides: 29