SlideShare a Scribd company logo
Templates
Object Oriented Programming Copyright © 2012 IM
Group. All rights
reserved
Training
• Makes a simple function to swap 2 characters.
Copyright © 2012 IM
Group. All rights
reserved
swap_values for char
• Here is a version of swap_values to swap
character variables:
▫ void swap_values(char& v1, char& v2)
{
char temp;
temp = v1;
v1 = v2;
v2 = temp;
}
Copyright © 2012 IM
Group. All rights
reserved
A General swap_values
• A generalized version of swap_values is shown
here.
▫ void swap_values(type_of_var& v1, type_of_var& v2)
{
type_of_var temp;
temp = v1;
v1 = v2;
v2 = temp;
}
▫ This function, if type_of_var could accept any type,
could be used to swap values of any type
Copyright © 2012 IM
Group. All rights
reserved
• A C++ function template will allow swap_values
to swap values of two variables of the same type
▫ Example:
template<class T>
void swap_values(T& v1, T& v2)
{
T temp;
temp = v1;
v1 = v2;
v = temp;
}
Template prefix
Type parameter
Templates for Functions
Copyright © 2012 IM
Group. All rights
reserved
Template Details
• template<class T> is the template prefix
▫ Tells compiler that the declaration or definition that
follows is a template
▫ Tells compiler that T is a type parameter
 class means type in this context
(typename could replace class but class is usually used)
 T can be replaced by any type argument
(whether the type is a class or not)
• A template overloads the function name by
replacing T with the type used in a function call
Copyright © 2012 IM
Group. All rights
reserved
Calling a Template Function
• Calling a function defined with a template is
identical to calling a normal function
▫ Example:
To call the template version of swap_values
char s1, s2;
int i1, i2;
…
swap_values(s1, s2);
swap_values(i1, i2);
 The compiler checks the argument types and
generates an appropriate version of swap_values
Copyright © 2012 IM
Group. All rights
reserved
Templates and Declarations
• A function template may also have a separate
declaration
▫ The template prefix and type parameter are used
▫ Depending on your compiler
 You may, or may not, be able to separate declaration and
definitions of template functions just as you do with regular
functions
▫ To be safe, place template function definitions in the same file
where they are used…with no declaration
 A file included with #include is, in most cases, equivalent to
being "in the same file“
 This means including the .cpp file or .h file with
implementation code
Copyright © 2012 IM
Group. All rights
reserved
Templates with Multiple Parameters
• Function templates may use more than one
parameter
▫ Example:
template<class T1, class T2>
 All parameters must be used in the template
function
Copyright © 2012 IM
Group. All rights
reserved
Defining Templates
• When defining a template it is a good idea…
▫ To start with an ordinary function that
accomplishes the task with one type
 It is often easier to deal with a concrete case rather
than the general case
▫ Then debug the ordinary function
▫ Next convert the function to a template by
replacing type names with a type parameter
Copyright © 2012 IM
Group. All rights
reserved
Copyright ©
2012 IM
Group. All
rights reserved
Templates for Data Abstraction
Object Oriented Programming
Templates for Data Abstraction
• Class definitions can also be made more general
with templates
▫ The syntax for class templates is basically the
same as for function templates
 template<class T> comes before the template
definition
 Type parameter T is used in the class definition just
like any other type
 Type parameter T can represent any type
Copyright © 2012 IM
Group. All rights
reserved
A Class Template
• The following is a class template
▫ An object of this class contains a pair of values of
type T
▫ template <class T>
class Pair
{
public:
Pair( );
Pair( T first_value, T second_value);
…
continued on next slide
Copyright © 2012 IM
Group. All rights
reserved
Template Class Pair (cont.)
▫ void set_element(int position, T value);
//Precondition: position is 1 or 2
//Postcondition: position indicated is set to value
T get_element(int position) const;
// Precondition: position is 1 or 2
// Returns value in position indicated
private:
T first;
T second;
};
Copyright © 2012 IM
Group. All rights
reserved
Declaring Template Class Objects
• Once the class template is defined, objects may
be declared
▫ Declarations must indicate what type is to be used
for T
▫ Example: To declare an object so it can hold a
pair of integers:
Pair<int> score;
or for a pair of characters:
Pair<char> seats;
Copyright © 2012 IM
Group. All rights
reserved
Using the Objects
• After declaration, objects based on a template
class are used just like any other objects
▫ Continuing the previous example:
score.set_element(1,3);
score.set_element(2,0);
seats.set_element(1, 'A');
Copyright © 2012 IM
Group. All rights
reserved
Defining the Member Functions
• Member functions of a template class are
defined
the same way as member functions of ordinary
classes
▫ The only difference is that the member function
definitions are themselves templates
Copyright © 2012 IM
Group. All rights
reserved
• This is a definition of the constructor for class
Pair that takes two arguments
template<class T>
Pair<T>::Pair(T first_value, T second_value)
: first(first_value), second(second_value)
{
//No body needed due to initialization above
}
▫ The class name includes <T>
Defining a Pair Constructor
Copyright © 2012 IM
Group. All rights
reserved
Defining set_element
• Here is a definition for set_element in the
template class Pair
void Pair<T>::set_element(int position, T value)
{
if (position = = 1)
first = value;
else if (position = = 2)
second = value;
else
…
}
Copyright © 2012 IM
Group. All rights
reserved
Template Class Names as Parameters
• The name of a template class may be used as the
type of a function parameter
▫ Example: To create a parameter of type
Pair<int>:
int add_up(const Pair<int>& the_pair);
//Returns the sum of two integers in the_pair
Copyright © 2012 IM
Group. All rights
reserved
Template Functions with Template
Class Parameters
• Function add_up from a previous example can
be made more general as a template function:
template<class T>
T add_up(const Pair<T>& the_pair)
//Precondition: operator + is defined for T
//Returns sum of the two values in
the_pair
Copyright © 2012 IM
Group. All rights
reserved
typedef and Templates
• You specialize a class template by giving a type
argument to the class name such as Pair<int>
▫ The specialized name, Pair<int>, is used just
like any class name
• You can define a new class type name with the
same meaning as the specialized name:
typedef Class_Name<Type_Arg>
New_Type_Name;
For example: typedef Pair<int> PairOfInt;
PairOfInt pair1, pair2;
Copyright © 2012 IM
Group. All rights
reserved
Any Questions
Session 6 Copyright © 2012 IM
Group. All rights
reserved

More Related Content

What's hot

حصص رياضيات باستراتيجيات كيجن
حصص رياضيات باستراتيجيات كيجن حصص رياضيات باستراتيجيات كيجن
حصص رياضيات باستراتيجيات كيجن
mansour1911
 
New cv chef (1)
New cv chef (1)New cv chef (1)
New cv chef (1)
Chef Kashi Rao
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
Thuan Nguyen
 
OOP C++
OOP C++OOP C++
OOP C++
Ahmed Farag
 
Top 20 Asp.net interview Question and answers
Top 20 Asp.net interview Question and answersTop 20 Asp.net interview Question and answers
Top 20 Asp.net interview Question and answers
w3asp dotnet
 
سيرة ذاتية - محمد محب
سيرة ذاتية - محمد محبسيرة ذاتية - محمد محب
سيرة ذاتية - محمد محبMohamed Moheb
 
‏‏نماذج دمج التقنية Tpack
‏‏نماذج دمج التقنية   Tpack‏‏نماذج دمج التقنية   Tpack
‏‏نماذج دمج التقنية Tpack
عبدالله يحي
 

What's hot (11)

حصص رياضيات باستراتيجيات كيجن
حصص رياضيات باستراتيجيات كيجن حصص رياضيات باستراتيجيات كيجن
حصص رياضيات باستراتيجيات كيجن
 
C.V. Sherook two
C.V.  Sherook twoC.V.  Sherook two
C.V. Sherook two
 
Asst. Pastry Chef CV
Asst. Pastry Chef CVAsst. Pastry Chef CV
Asst. Pastry Chef CV
 
New cv chef (1)
New cv chef (1)New cv chef (1)
New cv chef (1)
 
SQL
SQLSQL
SQL
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
OOP C++
OOP C++OOP C++
OOP C++
 
Top 20 Asp.net interview Question and answers
Top 20 Asp.net interview Question and answersTop 20 Asp.net interview Question and answers
Top 20 Asp.net interview Question and answers
 
c.v Mohamed Hosny
c.v Mohamed Hosnyc.v Mohamed Hosny
c.v Mohamed Hosny
 
سيرة ذاتية - محمد محب
سيرة ذاتية - محمد محبسيرة ذاتية - محمد محب
سيرة ذاتية - محمد محب
 
‏‏نماذج دمج التقنية Tpack
‏‏نماذج دمج التقنية   Tpack‏‏نماذج دمج التقنية   Tpack
‏‏نماذج دمج التقنية Tpack
 

Similar to OOP - Templates

Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
guestf0562b
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
Garik Kalashyan
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++TemplatesGanesh Samarthyam
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
Saiganesh124618
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
Jayfee Ramos
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
kinan keshkeh
 
[GRCPP] Introduction to concepts (C++20)
[GRCPP] Introduction to concepts (C++20)[GRCPP] Introduction to concepts (C++20)
[GRCPP] Introduction to concepts (C++20)
Dimitrios Platis
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
BlackRabbitCoder
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
Sasha Goldshtein
 
OOP - Introduction to Inheritance
OOP - Introduction to InheritanceOOP - Introduction to Inheritance
OOP - Introduction to Inheritance
Mohammad Shaker
 
Templates
TemplatesTemplates
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
Templates2
Templates2Templates2
Templates2
zindadili
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
Andrey Upadyshev
 

Similar to OOP - Templates (20)

Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Savitch ch 17
Savitch ch 17Savitch ch 17
Savitch ch 17
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++Templates
 
Java Generics
Java GenericsJava Generics
Java Generics
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 
[GRCPP] Introduction to concepts (C++20)
[GRCPP] Introduction to concepts (C++20)[GRCPP] Introduction to concepts (C++20)
[GRCPP] Introduction to concepts (C++20)
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
 
OOP - Introduction to Inheritance
OOP - Introduction to InheritanceOOP - Introduction to Inheritance
OOP - Introduction to Inheritance
 
Templates
TemplatesTemplates
Templates
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Templates2
Templates2Templates2
Templates2
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
 

More from Mohammad Shaker

Android Development - Session 5
Android Development - Session 5Android Development - Session 5
Android Development - Session 5
Mohammad Shaker
 
Android Development - Session 4
Android Development - Session 4Android Development - Session 4
Android Development - Session 4
Mohammad Shaker
 
Android Development - Session 2
Android Development - Session 2Android Development - Session 2
Android Development - Session 2
Mohammad Shaker
 
Android Development - Session 1
Android Development - Session 1Android Development - Session 1
Android Development - Session 1
Mohammad Shaker
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
Mohammad Shaker
 
OOP - STL
OOP - STLOOP - STL
OOP - STL
Mohammad Shaker
 
OOP - Friend Functions
OOP - Friend FunctionsOOP - Friend Functions
OOP - Friend Functions
Mohammad Shaker
 
OOP - Introduction
OOP - IntroductionOOP - Introduction
OOP - Introduction
Mohammad Shaker
 
NoSQL - A Closer Look to Couchbase
NoSQL - A Closer Look to CouchbaseNoSQL - A Closer Look to Couchbase
NoSQL - A Closer Look to Couchbase
Mohammad Shaker
 
Introduction to Couchbase
Introduction to CouchbaseIntroduction to Couchbase
Introduction to Couchbase
Mohammad Shaker
 

More from Mohammad Shaker (10)

Android Development - Session 5
Android Development - Session 5Android Development - Session 5
Android Development - Session 5
 
Android Development - Session 4
Android Development - Session 4Android Development - Session 4
Android Development - Session 4
 
Android Development - Session 2
Android Development - Session 2Android Development - Session 2
Android Development - Session 2
 
Android Development - Session 1
Android Development - Session 1Android Development - Session 1
Android Development - Session 1
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
OOP - STL
OOP - STLOOP - STL
OOP - STL
 
OOP - Friend Functions
OOP - Friend FunctionsOOP - Friend Functions
OOP - Friend Functions
 
OOP - Introduction
OOP - IntroductionOOP - Introduction
OOP - Introduction
 
NoSQL - A Closer Look to Couchbase
NoSQL - A Closer Look to CouchbaseNoSQL - A Closer Look to Couchbase
NoSQL - A Closer Look to Couchbase
 
Introduction to Couchbase
Introduction to CouchbaseIntroduction to Couchbase
Introduction to Couchbase
 

Recently uploaded

Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 

Recently uploaded (20)

Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 

OOP - Templates

  • 1. Templates Object Oriented Programming Copyright © 2012 IM Group. All rights reserved
  • 2. Training • Makes a simple function to swap 2 characters. Copyright © 2012 IM Group. All rights reserved
  • 3. swap_values for char • Here is a version of swap_values to swap character variables: ▫ void swap_values(char& v1, char& v2) { char temp; temp = v1; v1 = v2; v2 = temp; } Copyright © 2012 IM Group. All rights reserved
  • 4. A General swap_values • A generalized version of swap_values is shown here. ▫ void swap_values(type_of_var& v1, type_of_var& v2) { type_of_var temp; temp = v1; v1 = v2; v2 = temp; } ▫ This function, if type_of_var could accept any type, could be used to swap values of any type Copyright © 2012 IM Group. All rights reserved
  • 5. • A C++ function template will allow swap_values to swap values of two variables of the same type ▫ Example: template<class T> void swap_values(T& v1, T& v2) { T temp; temp = v1; v1 = v2; v = temp; } Template prefix Type parameter Templates for Functions Copyright © 2012 IM Group. All rights reserved
  • 6. Template Details • template<class T> is the template prefix ▫ Tells compiler that the declaration or definition that follows is a template ▫ Tells compiler that T is a type parameter  class means type in this context (typename could replace class but class is usually used)  T can be replaced by any type argument (whether the type is a class or not) • A template overloads the function name by replacing T with the type used in a function call Copyright © 2012 IM Group. All rights reserved
  • 7. Calling a Template Function • Calling a function defined with a template is identical to calling a normal function ▫ Example: To call the template version of swap_values char s1, s2; int i1, i2; … swap_values(s1, s2); swap_values(i1, i2);  The compiler checks the argument types and generates an appropriate version of swap_values Copyright © 2012 IM Group. All rights reserved
  • 8. Templates and Declarations • A function template may also have a separate declaration ▫ The template prefix and type parameter are used ▫ Depending on your compiler  You may, or may not, be able to separate declaration and definitions of template functions just as you do with regular functions ▫ To be safe, place template function definitions in the same file where they are used…with no declaration  A file included with #include is, in most cases, equivalent to being "in the same file“  This means including the .cpp file or .h file with implementation code Copyright © 2012 IM Group. All rights reserved
  • 9. Templates with Multiple Parameters • Function templates may use more than one parameter ▫ Example: template<class T1, class T2>  All parameters must be used in the template function Copyright © 2012 IM Group. All rights reserved
  • 10. Defining Templates • When defining a template it is a good idea… ▫ To start with an ordinary function that accomplishes the task with one type  It is often easier to deal with a concrete case rather than the general case ▫ Then debug the ordinary function ▫ Next convert the function to a template by replacing type names with a type parameter Copyright © 2012 IM Group. All rights reserved
  • 11. Copyright © 2012 IM Group. All rights reserved Templates for Data Abstraction Object Oriented Programming
  • 12. Templates for Data Abstraction • Class definitions can also be made more general with templates ▫ The syntax for class templates is basically the same as for function templates  template<class T> comes before the template definition  Type parameter T is used in the class definition just like any other type  Type parameter T can represent any type Copyright © 2012 IM Group. All rights reserved
  • 13. A Class Template • The following is a class template ▫ An object of this class contains a pair of values of type T ▫ template <class T> class Pair { public: Pair( ); Pair( T first_value, T second_value); … continued on next slide Copyright © 2012 IM Group. All rights reserved
  • 14. Template Class Pair (cont.) ▫ void set_element(int position, T value); //Precondition: position is 1 or 2 //Postcondition: position indicated is set to value T get_element(int position) const; // Precondition: position is 1 or 2 // Returns value in position indicated private: T first; T second; }; Copyright © 2012 IM Group. All rights reserved
  • 15. Declaring Template Class Objects • Once the class template is defined, objects may be declared ▫ Declarations must indicate what type is to be used for T ▫ Example: To declare an object so it can hold a pair of integers: Pair<int> score; or for a pair of characters: Pair<char> seats; Copyright © 2012 IM Group. All rights reserved
  • 16. Using the Objects • After declaration, objects based on a template class are used just like any other objects ▫ Continuing the previous example: score.set_element(1,3); score.set_element(2,0); seats.set_element(1, 'A'); Copyright © 2012 IM Group. All rights reserved
  • 17. Defining the Member Functions • Member functions of a template class are defined the same way as member functions of ordinary classes ▫ The only difference is that the member function definitions are themselves templates Copyright © 2012 IM Group. All rights reserved
  • 18. • This is a definition of the constructor for class Pair that takes two arguments template<class T> Pair<T>::Pair(T first_value, T second_value) : first(first_value), second(second_value) { //No body needed due to initialization above } ▫ The class name includes <T> Defining a Pair Constructor Copyright © 2012 IM Group. All rights reserved
  • 19. Defining set_element • Here is a definition for set_element in the template class Pair void Pair<T>::set_element(int position, T value) { if (position = = 1) first = value; else if (position = = 2) second = value; else … } Copyright © 2012 IM Group. All rights reserved
  • 20. Template Class Names as Parameters • The name of a template class may be used as the type of a function parameter ▫ Example: To create a parameter of type Pair<int>: int add_up(const Pair<int>& the_pair); //Returns the sum of two integers in the_pair Copyright © 2012 IM Group. All rights reserved
  • 21. Template Functions with Template Class Parameters • Function add_up from a previous example can be made more general as a template function: template<class T> T add_up(const Pair<T>& the_pair) //Precondition: operator + is defined for T //Returns sum of the two values in the_pair Copyright © 2012 IM Group. All rights reserved
  • 22. typedef and Templates • You specialize a class template by giving a type argument to the class name such as Pair<int> ▫ The specialized name, Pair<int>, is used just like any class name • You can define a new class type name with the same meaning as the specialized name: typedef Class_Name<Type_Arg> New_Type_Name; For example: typedef Pair<int> PairOfInt; PairOfInt pair1, pair2; Copyright © 2012 IM Group. All rights reserved
  • 23. Any Questions Session 6 Copyright © 2012 IM Group. All rights reserved