Templates in C++ (Part 2) - S.M. Riazul Islam,...

Post on 20-May-2020

1 views 0 download

transcript

Templates in C++(Part 2)

Contents

• Stack Implementation Using Class Templates

• Passing Class Template Objects to Function Templates

• Templates and Friends

• Templates and Inheritance

Stack Implementation Using Class Templates

• Stack: a data structure into which we insert elements at the top and retrieve those items in Last-In-First-Out (LIFO) principle.

• However, to instantiate a stack, a data type must be specified.

• Templates: to make it independent of the type of the items being placed in the stack.

Stack Using Templates: Stack Operations

Stack Using Templates

Stack.h(1/2)

Stack Using Templates

Stack.h(2/2)

Stack Using Templates

Main.CPP(1/2)

Stack Using Templates

Main.CPP(2/2)

Stack Using Templates

Passing a Stack template object to a function template

StackTemplateObject to Function

Passing a Stack template object to a function template

Non-Type Parameters and Default Types for Class Templates

• It’s also possible to use non-type template parameters, which can have default arguments and are treated as consts

Class Template and Class

• The declaration MyClassTemplate<int> is a class, or a class based on a template.

• There are no special properties of a class based on a template vs. a class not based on a template.

• The special properties are of the template itself.

Classes do not define templates, templates define classes

Templates and friends

• It is known to us that functions and entire classes can be declared as friends of nontemplate classes.

• With class templates friendship can be established

between a class template and a global function, a member function of another class(possibly a class-template specialization), or even an entire class (possibly a class-template specialization).

Templates and friends

Templates and friends

Templates Exercise 1

Templated friend function of a templated class

• Write a program to test the given approach for establishing the friendship between the template class and the friend function

Do you find any bad thing in this approach?

Templates and Inheritance

• A class template can be derived from a class-template specialization.

• A class template can be derived from a nontemplate class.

• A class-template specialization can be derived from a class-template specialization.

• A nontemplate class can be derived from a class-template specialization.

Template and Static Members

• Nontemplate class: One copy of each static data member is shared among all objects of the class, and the static data member must be initialized at global namespace scope.

• Each class-template specialization instantiated from a class template has its own copy of each static data member of the class template; all objects of that specialization share that one static data member.

Review: C++ Standard Library Class Template Vector

(Lecture Slides 7)