SlideShare a Scribd company logo
Templates
Jim Fawcett
CSE687 – Object Oriented Design
Spring 2010
2
Agenda: Now and Later
• Basic Templates and Specialization
– Simple Examples of template functions and classes
• Template parameters
– Types, integral values, and function pointers
• Template members
– Member functions of classes may be templates
• Partial Template Specialization
– Smart pointers
• Template Traits and Policies (later)
– Hash Table Example
• Standard Template Library (later)
– Containers, Iterators, and Algorithms
• Template Metaprogramming (later)
– Computation at compile time, with applications
3
Simple Examples
• Templates are patterns used to generate code,
instances of which, differ only in the symbolic use of a
type name.
• Templates allow us to write one function for an
unspecified type, and let the compiler fill in the details for
specific type instances.
• Consider the template function:
template<class T>
T max(const T& t1, const T& t2)
{
return ((t2 > t1) ? t2 : t1);
}
• This works beautifully as long as types we instantiate
have operations used to implement the function, in this
case a magnitude comparison.
4
Instantiation
• We instantiate the function, for some specific type, by invoking it:
int y = 1;
int x = max(2,y);
• The compiler infers template parameter type from the type of y.
• What do you think happens with:
string s = max(“zebra”,”aardvark”);
We will come back to this later.
5
Template Functions
• A function template is a declaration for a function which uses an unspecified type T
as a formal parameter, return value, or local variable.
template <typename T>
void swap(T& t1, T& t2) {
T temp = t1;
t1 = t2;
t2 = temp;
}
• None of the processing in this example depends on the actual type represented by
the generic parameter T. That’s a requirement for templates to succeed.
• Another requirement is that the generic type, T, possess the operations used in the
function definition. In this swap function, T is required to have an assignment
operator=(…) and a copy constructor, to build the temporary type T object temp, or
compiler generated copy and assigment must be valid.
• If these conditions are not met, compilation of the swap function may fail, or, if the
compiler can generate implied operations, the function’s semantics may not be what
you expect.
6
Template Classes
• Template-based classes are classes which depend on an
unspecified type as a:
– Formal parameter or return value of a member function.
– Local variable for a member function.
– Composed member of the class.
template <typename T> class stack {
public:
stack();
void push(const T& t);
T pop(void);
…
};
template <typename T>
stack<T>::stack() { … }
…
See Handouts/CSE687/code/Templates/Stack for more details.
7
Template Class Instantiation
• We instantiate a class by declaring the type of its parameter, like this:
stack<string> myStack;
stack<int> yourStack;
• The stack<string> class and stack<int> class are distinct types. Should
stack<T> declare a static data member, that member would be shared by all
stack<int> instances, but would not be shared by instances of stack<int>
with instances of stack<string>.
• Instantiation happens at application compile time, when the compiler sees
the concrete type associated with the template parameter. No code can be
generated before that time, as the size of T instances is not known.
– The consequence of this is that you must put all template function and class
method bodies in the header file, included with application code, so the compiler
sees the definition at the time the parameter is associated with a concrete type.
– Thus, we have a general rule:
Header files contain only:
» Declarations
» Template declarations and parameterized“definitions”
» Inline function definitions
8
Rewrite Rules
• A template-based class can be derived from a class that depends on a
specific type, say int, by using the following rules:
– Replace
class classname { … };
with
template <class T> class className { … };
– For each of the member functions, replace
returnType className::memName(…) { …}
with
template <class T>
returnType className<T>::memName(…) {…}
– Replace every object definition
className obj;
with
className<T> obj;
– Replace every occurrence of the specific type, say int, with the generic type
name T.
9
Template Parameters
• Types defined in applications and
libraries
template<class T> stack { … }
stack<Widget> myStack;
• Native types, e.g., int, double, …
template<class T, int i> buffer { … }
buffer<char,255> pathbuff;
• Other templates, called template
template paramters
template<class T, template <class T>
class V> myClass { … }
myClass<int, stack> mc;
instead of
myClass<int, stack<int> > mc;
• Constant expressions
enum thread_type { default, terminating };
template <thread_type>
class Thread { … };
Thread<default> myThread;
• Address of a function or object with
external linkage
template<class R, class A, R(*fptr)(A)>
class delegate { … }
delegate<int,double,mfunc> del;
Template parameters may be:
10
Template Members
• A class may define members to be templates
template <class T> class smartPtr {
public:
template <class U> smartPtr(U* pU);
smartPtr();
…
• This class declares a smart pointer and its template
member, smartPtr(U* pU), defines a promotion
constructor from type U* to smartPtr<T>.
11
Template Specializations
• The max function:
template<class T>
T max(const T& t1, const T& t2)
{
return ((t2 > t1) ? t2 : t1);
}
is fairly useless for literal strings. Their type is const char*, e.g., an address,
so max returns whichever string has the higher memory address, not the
lexocographically higher. Enter specialization.
• The C++ language guarantees that, should we replace T with a specific
type, then that specialization will be used whenever the compiler’s type
inference yields that type, e.g.:
typedef char* pChar;
template<>
const pChar max(const pChar& s1, const pChar& s2)
{
return ((strcmp(s1,s2)>0) ? S1 : s2);
}
12
Template Specializations
• A template specialization is the narrowing of the
number of types a template accepts as arguments,
possibly to one.
– template <class T> widget
– generic
– template <class T*> widget
– partial specialization to pointers
– template <> widget<std::string>
– full specialization to one concrete type.
– See PTS.cpp in cse687/code/templates
• We define specializations to treat those cases in
some special manner.
13
Specialization Targets
• All template classes can be specialized
– template <class T> class stack {…};
– template<> class stack<int> {…};
– Specializations need not provide exactly the same
members. You may add or delete members.
• template <class U, class V>
class Widget {…};
• template <class U>
class Wiget <U,int> {…}; // may add, modify, or remove
// members to suit int param
14
Partial Template Specialization
• A template class with two or more parameters may be
specialized partially, as well as completely.
– Fully generic class:
template<class U, class V> Widget { … };
Widget<string,double> myWidget;
– Partial specialization:
template<class U> Widget<U,double> { … };
Widget<string,double> yourWidget;
– Complete specialization:
template<> Widget<string,double> { … };
Widget<string,double> ourWidget;
15
Containers
• Containers are classes which implement data structures containing
objects of other classes:
– stacks, lists, queues, …
• Often the logic necessary to manage a container is independent of
its contents type, using the type only symbolically. These containers
may be implemented with templates to yield a generic container.
• If an operation of the generic type is needed by the container, say
assignment or comparison, then the type used to instantiate the
container must provide it. Otherwise compilation will fail.
• Example: if we expect to support binary search on a generic array of
objects: array<T> myArray, then the type T will need to support
assignment and comparison so we can sort the array.
16
Container Types
• Containers are classified as either:
– Homogeneous
Containers hold only on type of object. They
generalize an array of primitive types.
– Heterogeneous
Containers hold more than one type of object, usually
all belong to a common derivation hierarchy.
• If a container expects a reference to a base class object, it
will accept a reference to any type which is derived from the
base class.
• Upward type compatibility is the basis for flexible run-time
creation and management of objects.
17
Template Container Types
• If we implement a container with templates, it will be
homogeneous if we instantiate it with a a class with no
derivations or with a primitive type, e.g.:
array<char> myHomogeneousArray;
If, however, we instantiate the container with pointers to
the base class of a derivation hierarchy, then the same
design yields a heterogeneous container, e.g.:
array<myBaseClass*> myHeterogeneousArray;
The moral of this story is that you should always design
template containers as implicitly homgeneous, allowing
instantiation to determine the container type.
18
Container Semantics
• Containers are said to have either
– Value semantics:
Objects are copied into the container
– Reference semantics:
The container is passed a reference or pointer
to an external object.
19
Reference Semantics
• Container holds references to objects, e.g.,
pointers, C++ references, or handles.
• An object can be “in” more than one container
simultaneously
• Insertion does no copying
• When containers are destroyed, their objects are
not automatically destroyed
– So you have to manage those resources without help
from the container
20
Value Semantics
• Container holds the objects themselves.
• No object lives in more than one container.
• Objects are copied into the container, so the
container owns its objects.
– All contained objects must be the same size.
– Types must supply copy and assignment semantics
• When the container is destroyed, the objects are
also destroyed.
21
Container Semantics
• It is easy to simulate reference semantics by
using containers designed with value semantics,
but holding reference objects, e.g.:
array<myObjects*> CollectionOfPointers
• The moral of this story is that you should always
design containers with value semantics. If the
client wants reference semantics that’s easy to
arrange by using references to objects.
– The client then takes responsibility to manage the
references properly.
22
Container Iterators
• Iterators are objects designed to traverse a specific
container type.
• Often the container must grant the iterator friendship
status or provide member accessor functions designed
to allow the iterator to do its job.
• A container/iterator class pair generalizes the operations
of an array/pointer pair for primitive types.
– The iterator constructor makes the iterator “point” to an object in
the container.
– Often, the iterator has knowledge and access necessary to
traverse some, perhaps complex, internal structure in the
container, contained object-by-object.
23
Iterator Issues
• Either the designer or client must take care not to destroy a
container, or change allocations in a container, if it has active
iterators. The result would be a dangling reference.
– We will see later that it is easy to create invalid iterators on std::vector
objects by inserting or removing elements.
• Iterators are especially useful in cases where a container may need
to have more than one simultaneous traversal.
– This is a common need when implementing graph algorithms, for
example.
• There may also be more than one type of useful traversal, so
iterators can be designed for each type.
– Depth first search and breath first search on graphs are an example.
24
Conclusion
• Virtually everything we’ve discussed in this
presentation is a part of the design or use of the
Standard Template Library (STL).
• We will see all of these illustrated with examples,
throughout this course, starting with design of a
HashTable container.

More Related Content

PPTX
Lecture 27 - OOPSFAST NUCES ISB.ppsx.pptx
PPT
an introduction to c++ templates-comprehensive guide.ppt
PPT
2CPP15 - Templates
PPTX
TEMPLATES in C++ are one of important topics in Object Oriented Programming
PPTX
PPTX
Templates in c++
PPTX
Templates c++ - prashant odhavani - 160920107003
Lecture 27 - OOPSFAST NUCES ISB.ppsx.pptx
an introduction to c++ templates-comprehensive guide.ppt
2CPP15 - Templates
TEMPLATES in C++ are one of important topics in Object Oriented Programming
Templates in c++
Templates c++ - prashant odhavani - 160920107003

Similar to templates.ppt (20)

PDF
An Introduction To C++Templates
PPTX
Templates in c++
PPTX
Presentation 3rd
PPTX
Templates1
PPTX
Types, classes and concepts
PDF
C Programming - Refresher - Part IV
PDF
C++ Templates 2
PDF
Metaprogramming
PDF
PPTX
PPTX
Class template
PDF
DOC-20240718-WA0006..pdf34642235632567432
PPTX
Lec-21-Classes and Object Orientation.pptx
PPTX
C++ & Data Structure - Unit - first.pptx
PPTX
UNIT-2 OOM.pptxUNIT-2 OOM.pptxUNIT-2 OOM.pptx
PPTX
Lecture 25 - OOPFAST NUCES ISB.ppsx.pptx
PPTX
Typescript: Beginner to Advanced
PPTX
Generics Module 2Generics Module Generics Module 2.pptx
PPTX
Function Overloading Call by value and call by reference
An Introduction To C++Templates
Templates in c++
Presentation 3rd
Templates1
Types, classes and concepts
C Programming - Refresher - Part IV
C++ Templates 2
Metaprogramming
Class template
DOC-20240718-WA0006..pdf34642235632567432
Lec-21-Classes and Object Orientation.pptx
C++ & Data Structure - Unit - first.pptx
UNIT-2 OOM.pptxUNIT-2 OOM.pptxUNIT-2 OOM.pptx
Lecture 25 - OOPFAST NUCES ISB.ppsx.pptx
Typescript: Beginner to Advanced
Generics Module 2Generics Module Generics Module 2.pptx
Function Overloading Call by value and call by reference
Ad

Recently uploaded (20)

PPTX
Custom Software Development Services.pptx.pptx
PPTX
Introduction to Windows Operating System
PDF
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
PDF
MCP Security Tutorial - Beginner to Advanced
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PPTX
Trending Python Topics for Data Visualization in 2025
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PPTX
Cybersecurity: Protecting the Digital World
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PPTX
Patient Appointment Booking in Odoo with online payment
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PDF
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PDF
Website Design Services for Small Businesses.pdf
PPTX
Tech Workshop Escape Room Tech Workshop
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PDF
Wondershare Recoverit Full Crack New Version (Latest 2025)
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Custom Software Development Services.pptx.pptx
Introduction to Windows Operating System
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
MCP Security Tutorial - Beginner to Advanced
Advanced SystemCare Ultimate Crack + Portable (2025)
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
Trending Python Topics for Data Visualization in 2025
Weekly report ppt - harsh dattuprasad patel.pptx
Cybersecurity: Protecting the Digital World
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Patient Appointment Booking in Odoo with online payment
Monitoring Stack: Grafana, Loki & Promtail
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
Oracle Fusion HCM Cloud Demo for Beginners
Website Design Services for Small Businesses.pdf
Tech Workshop Escape Room Tech Workshop
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
Wondershare Recoverit Full Crack New Version (Latest 2025)
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Ad

templates.ppt

  • 1. Templates Jim Fawcett CSE687 – Object Oriented Design Spring 2010
  • 2. 2 Agenda: Now and Later • Basic Templates and Specialization – Simple Examples of template functions and classes • Template parameters – Types, integral values, and function pointers • Template members – Member functions of classes may be templates • Partial Template Specialization – Smart pointers • Template Traits and Policies (later) – Hash Table Example • Standard Template Library (later) – Containers, Iterators, and Algorithms • Template Metaprogramming (later) – Computation at compile time, with applications
  • 3. 3 Simple Examples • Templates are patterns used to generate code, instances of which, differ only in the symbolic use of a type name. • Templates allow us to write one function for an unspecified type, and let the compiler fill in the details for specific type instances. • Consider the template function: template<class T> T max(const T& t1, const T& t2) { return ((t2 > t1) ? t2 : t1); } • This works beautifully as long as types we instantiate have operations used to implement the function, in this case a magnitude comparison.
  • 4. 4 Instantiation • We instantiate the function, for some specific type, by invoking it: int y = 1; int x = max(2,y); • The compiler infers template parameter type from the type of y. • What do you think happens with: string s = max(“zebra”,”aardvark”); We will come back to this later.
  • 5. 5 Template Functions • A function template is a declaration for a function which uses an unspecified type T as a formal parameter, return value, or local variable. template <typename T> void swap(T& t1, T& t2) { T temp = t1; t1 = t2; t2 = temp; } • None of the processing in this example depends on the actual type represented by the generic parameter T. That’s a requirement for templates to succeed. • Another requirement is that the generic type, T, possess the operations used in the function definition. In this swap function, T is required to have an assignment operator=(…) and a copy constructor, to build the temporary type T object temp, or compiler generated copy and assigment must be valid. • If these conditions are not met, compilation of the swap function may fail, or, if the compiler can generate implied operations, the function’s semantics may not be what you expect.
  • 6. 6 Template Classes • Template-based classes are classes which depend on an unspecified type as a: – Formal parameter or return value of a member function. – Local variable for a member function. – Composed member of the class. template <typename T> class stack { public: stack(); void push(const T& t); T pop(void); … }; template <typename T> stack<T>::stack() { … } … See Handouts/CSE687/code/Templates/Stack for more details.
  • 7. 7 Template Class Instantiation • We instantiate a class by declaring the type of its parameter, like this: stack<string> myStack; stack<int> yourStack; • The stack<string> class and stack<int> class are distinct types. Should stack<T> declare a static data member, that member would be shared by all stack<int> instances, but would not be shared by instances of stack<int> with instances of stack<string>. • Instantiation happens at application compile time, when the compiler sees the concrete type associated with the template parameter. No code can be generated before that time, as the size of T instances is not known. – The consequence of this is that you must put all template function and class method bodies in the header file, included with application code, so the compiler sees the definition at the time the parameter is associated with a concrete type. – Thus, we have a general rule: Header files contain only: » Declarations » Template declarations and parameterized“definitions” » Inline function definitions
  • 8. 8 Rewrite Rules • A template-based class can be derived from a class that depends on a specific type, say int, by using the following rules: – Replace class classname { … }; with template <class T> class className { … }; – For each of the member functions, replace returnType className::memName(…) { …} with template <class T> returnType className<T>::memName(…) {…} – Replace every object definition className obj; with className<T> obj; – Replace every occurrence of the specific type, say int, with the generic type name T.
  • 9. 9 Template Parameters • Types defined in applications and libraries template<class T> stack { … } stack<Widget> myStack; • Native types, e.g., int, double, … template<class T, int i> buffer { … } buffer<char,255> pathbuff; • Other templates, called template template paramters template<class T, template <class T> class V> myClass { … } myClass<int, stack> mc; instead of myClass<int, stack<int> > mc; • Constant expressions enum thread_type { default, terminating }; template <thread_type> class Thread { … }; Thread<default> myThread; • Address of a function or object with external linkage template<class R, class A, R(*fptr)(A)> class delegate { … } delegate<int,double,mfunc> del; Template parameters may be:
  • 10. 10 Template Members • A class may define members to be templates template <class T> class smartPtr { public: template <class U> smartPtr(U* pU); smartPtr(); … • This class declares a smart pointer and its template member, smartPtr(U* pU), defines a promotion constructor from type U* to smartPtr<T>.
  • 11. 11 Template Specializations • The max function: template<class T> T max(const T& t1, const T& t2) { return ((t2 > t1) ? t2 : t1); } is fairly useless for literal strings. Their type is const char*, e.g., an address, so max returns whichever string has the higher memory address, not the lexocographically higher. Enter specialization. • The C++ language guarantees that, should we replace T with a specific type, then that specialization will be used whenever the compiler’s type inference yields that type, e.g.: typedef char* pChar; template<> const pChar max(const pChar& s1, const pChar& s2) { return ((strcmp(s1,s2)>0) ? S1 : s2); }
  • 12. 12 Template Specializations • A template specialization is the narrowing of the number of types a template accepts as arguments, possibly to one. – template <class T> widget – generic – template <class T*> widget – partial specialization to pointers – template <> widget<std::string> – full specialization to one concrete type. – See PTS.cpp in cse687/code/templates • We define specializations to treat those cases in some special manner.
  • 13. 13 Specialization Targets • All template classes can be specialized – template <class T> class stack {…}; – template<> class stack<int> {…}; – Specializations need not provide exactly the same members. You may add or delete members. • template <class U, class V> class Widget {…}; • template <class U> class Wiget <U,int> {…}; // may add, modify, or remove // members to suit int param
  • 14. 14 Partial Template Specialization • A template class with two or more parameters may be specialized partially, as well as completely. – Fully generic class: template<class U, class V> Widget { … }; Widget<string,double> myWidget; – Partial specialization: template<class U> Widget<U,double> { … }; Widget<string,double> yourWidget; – Complete specialization: template<> Widget<string,double> { … }; Widget<string,double> ourWidget;
  • 15. 15 Containers • Containers are classes which implement data structures containing objects of other classes: – stacks, lists, queues, … • Often the logic necessary to manage a container is independent of its contents type, using the type only symbolically. These containers may be implemented with templates to yield a generic container. • If an operation of the generic type is needed by the container, say assignment or comparison, then the type used to instantiate the container must provide it. Otherwise compilation will fail. • Example: if we expect to support binary search on a generic array of objects: array<T> myArray, then the type T will need to support assignment and comparison so we can sort the array.
  • 16. 16 Container Types • Containers are classified as either: – Homogeneous Containers hold only on type of object. They generalize an array of primitive types. – Heterogeneous Containers hold more than one type of object, usually all belong to a common derivation hierarchy. • If a container expects a reference to a base class object, it will accept a reference to any type which is derived from the base class. • Upward type compatibility is the basis for flexible run-time creation and management of objects.
  • 17. 17 Template Container Types • If we implement a container with templates, it will be homogeneous if we instantiate it with a a class with no derivations or with a primitive type, e.g.: array<char> myHomogeneousArray; If, however, we instantiate the container with pointers to the base class of a derivation hierarchy, then the same design yields a heterogeneous container, e.g.: array<myBaseClass*> myHeterogeneousArray; The moral of this story is that you should always design template containers as implicitly homgeneous, allowing instantiation to determine the container type.
  • 18. 18 Container Semantics • Containers are said to have either – Value semantics: Objects are copied into the container – Reference semantics: The container is passed a reference or pointer to an external object.
  • 19. 19 Reference Semantics • Container holds references to objects, e.g., pointers, C++ references, or handles. • An object can be “in” more than one container simultaneously • Insertion does no copying • When containers are destroyed, their objects are not automatically destroyed – So you have to manage those resources without help from the container
  • 20. 20 Value Semantics • Container holds the objects themselves. • No object lives in more than one container. • Objects are copied into the container, so the container owns its objects. – All contained objects must be the same size. – Types must supply copy and assignment semantics • When the container is destroyed, the objects are also destroyed.
  • 21. 21 Container Semantics • It is easy to simulate reference semantics by using containers designed with value semantics, but holding reference objects, e.g.: array<myObjects*> CollectionOfPointers • The moral of this story is that you should always design containers with value semantics. If the client wants reference semantics that’s easy to arrange by using references to objects. – The client then takes responsibility to manage the references properly.
  • 22. 22 Container Iterators • Iterators are objects designed to traverse a specific container type. • Often the container must grant the iterator friendship status or provide member accessor functions designed to allow the iterator to do its job. • A container/iterator class pair generalizes the operations of an array/pointer pair for primitive types. – The iterator constructor makes the iterator “point” to an object in the container. – Often, the iterator has knowledge and access necessary to traverse some, perhaps complex, internal structure in the container, contained object-by-object.
  • 23. 23 Iterator Issues • Either the designer or client must take care not to destroy a container, or change allocations in a container, if it has active iterators. The result would be a dangling reference. – We will see later that it is easy to create invalid iterators on std::vector objects by inserting or removing elements. • Iterators are especially useful in cases where a container may need to have more than one simultaneous traversal. – This is a common need when implementing graph algorithms, for example. • There may also be more than one type of useful traversal, so iterators can be designed for each type. – Depth first search and breath first search on graphs are an example.
  • 24. 24 Conclusion • Virtually everything we’ve discussed in this presentation is a part of the design or use of the Standard Template Library (STL). • We will see all of these illustrated with examples, throughout this course, starting with design of a HashTable container.